Click here to Skip to main content
14,599,610 members
Rate this:
Please Sign up or sign in to vote.
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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:
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:
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.
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100