I have found a solution on here to play a sound file in WPF which I extracted into a method and call this method in another method. But the when the PlaySound()
is called the sound doesn't play. Does anyone have any insight as to why this is happening? Also the sound files are marked as content, but changing to type resource didn't remedy the problem either?
My method to play a sound:
private void PlaySound()
{
Uri uri = new Uri(@"pack://application:,,,/Sounds/jabSound.wav");
var player = new MediaPlayer();
player.Open(uri);
player.Play();
}
Then I call the method like this but its doesn't play the sound file, PlaySound();
For Windows, if you double-click a WAV file, it will open using Windows Media Player. For Mac, if you double-click a WAV, it will open using iTunes or Quicktime. If you're on a system without these programs installed, then consider third-party software. We recommend Audacity for its extensive features and ease-of-use.
You can play MP3s with lots of different computer software, including the default music player in Windows, VLC, iTunes, Winamp, and most other music players. Apple devices like the iPhone, iPad and iPod touch can play MP3 files without a special app, like from right within the web browser or Mail app.
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.
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, thisURI
doesn’t use the application pack syntax
, so it’s not possible to embed an audio file and play it using theMediaPlayer
class. This limitation is because theMediaPlayer
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With