How to play a sound file?

It turns out that MediaPlayer does not play the music files in embedded resources, quote from Matthew MacDonald book: Pro WPF 4.5 in C#. Chapter 26:

You supply the location of your file as a URI. Unfortunately, this URI doesn’t use the application pack syntax, so it’s not possible to embed an audio file and play it using the MediaPlayer class. This limitation is because the MediaPlayer class is built on functionality that’s not native to WPF—instead, it’s provided by a distinct, unmanaged component of the Windows Media Player.

Therefore, try setting the local path to the your music file:

private void PlaySound()
{
    var uri = new Uri(@"your_local_path", UriKind.RelativeOrAbsolute);
    var player = new MediaPlayer();

    player.Open(uri);
    player.Play();
}

For workaround, see this link:

Playing embedded audio files in WPF


You could also use a SoundPlayer

SoundPlayer player = new SoundPlayer(path);
player.Load();
player.Play();

Pretty self explanatory.

BONUS Here's how to have it loop through asynchronously.

bool soundFinished = true;

if (soundFinished)
{
    soundFinished = false;
    Task.Factory.StartNew(() => { player.PlaySync(); soundFinished = true; });
} 

Opens a task to play the sound, waits until the sound is finished, then knows it is finished and plays again.


In addition to @Anatoly's answer, I would suggest to listen to MediaFailed event to check for MediaPlayer failure (such as file not found due to wrong path to your .wav file). MediaPlayer doesn't throw exception if it fails to load the media file, it triggers MediaFailed event instead.

And if you're trying to use relative uri, remember that it means relative to your executable file location. In development phase, it is usually inside bin\debug folder. So path to your .wav file should be "../../Sounds/jabSound.wav".

Uri uri = new Uri("../../Sounds/jabSound.wav", UriKind.Relative);
var player = new MediaPlayer();
player.MediaFailed += (o, args) =>
                      {
                          //here you can get hint of what causes the failure 
                          //from method parameter args 
                      };
player.Open(uri);
player.Play();

Tags:

C#

Wpf

Audio