C#C
C#3y ago
Matt

❔ MediaPlayer in WPF occasionally fails

        public static void PlaySound(string path)
        {
            Task.Run(() =>
            {
                MediaPlayer player = new();
                Task.Delay(50).Wait();
                Uri uri = new(path);
                player.Open(uri);
                player.Volume = 0.1;
                player.Play();
                Task.Delay((int)player.NaturalDuration.TimeSpan.TotalMilliseconds).Wait();
                player.Stop();
                player.Close();
            });
        }

I'm using this fire-forget pattern to play a sound through the media player. Sometimes the sound simply refuses to play. After the app has been open for long enough, all sound completely refuses to play no matter what. Any idea why?
Was this page helpful?