Click here to Skip to main content
15,889,200 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone, i am trying to play a simple .wav file for background music but for some reason after about 10 - 30 seconds of playing it always stops without any kind of error popping up. I am using visual studio 2017 to run it so when it stops i have found that a marker is placed at the time it stops and it indicates the start of a managed heap garbage collection (GC), but i have no idea how to fix this so if someone could tell me how to fix this problem or put forward another way of playing audio without this problem please share, it would be greatly appreciated.

What I have tried:

private void PlaySound()
        {
            Uri uri = new Uri(@"C:\User Program Files\ConsoleApp1\visual studio\Mini test game 1\Mini test game 1\resources\Sad Background Music 1.wav");
            var player = new MediaPlayer();
            player.Open(uri);
            player.Play();
        }
Posted
Updated 19-Oct-19 22:41pm

1 solution

Quote:
i have found that a marker is placed at the time it stops and it indicates the start of a managed heap garbage collection (GC)
That does kinda say exactly what the problem is!
Your player is going out of scope at the end of teh method, so there are no references in your app to it any more:
C#
private void PlaySound()
{
    Uri uri = new Uri(@"C:\User Program Files\ConsoleApp1\visual studio\Mini test game 1\Mini test game 1\resources\Sad Background Music 1.wav");
    var player = new MediaPlayer();
    player.Open(uri);
    player.Play();
}
As a result, when the GC kicks in it finds an unreferenced object and deletes it. That stops the player playing!

Move your player outside the method and it'l retain the reference and prevent teh GC removing it:
C#
private MediaPlayer player = new MediaPlayer();
private void PlaySound()
{
    Uri uri = new Uri(@"C:\User Program Files\ConsoleApp1\visual studio\Mini test game 1\Mini test game 1\resources\Sad Background Music 1.wav");
    player.Open(uri);
    player.Play();
}

But do yourself a favour: don't hard code your URL: use a settings file, or a relative-to-the-app-executable folder instead. That way, your app doesn't go tits-up when you give a copy to your mate.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900