So I’m making a small WPF game, which you can find here by the way ✨, and I come across a confusing and infuriating issue. WPF has two built-in audio players: SoundPlayer and MediaPlayer.
- SoundPlayer: Can play audio files that are embedded resources in the application, however, this can only play one sound at once.
- MediaPlayer: Cannot play audio files that are embedded resources in the application, however, this can play multiple sounds at once.
I think you can see the issue I was having. I wanted to play some background music in my game as well as some sound effects for certain actions in the game. This meant the easiest way to get this functionality was to use both of these options and save the background music to the local disk as a temporary file. Not as clean as I wanted, but it will do I guess 🤷♂️
First, I set up my SoundPlayer as this was the simplest one of the two. I created a new SoundPlayer object using the embedded resource:
private static readonly SoundPlayer _soundOne = new SoundPlayer(WPF.Properties.Resources.soundOne);
Then when I wanted this sound to play, I would simply use:
This is used as a temporary sound effect. In the game, it’s used as the ‘smacking’ sound effect.
Simple enough for the SoundPlayer… Now we move on to the MediaPlayer.
First, I make sure that my audio file is set as an Embedded Resource under the Build Actions in the file’s properties in Visual Studio:
You can see from the screenshot above, that I have a WAV file called “backgroundmusic.wav” which I need to save to disk, play continuously and then delete once the game is closed.
Now that we have done this, we can create the method for saving the embedded WAV file to the %temp% location on disk. This is how I did that:
Great, we have now saved the embedded resource to disk, how can we play this now? 🤔
We play this by creating a new MediaPlayer object and using the temp file location to play the audio. My…