How to play two sound file at the same time with WPF?

Alan lau picture Alan lau · Dec 18, 2012 · Viewed 9.1k times · Source

I use SoundPlayer to play sound effects in the WPF program. However, I find that when two sounds effects are played at the same time, the new one will replace the old one (i.e. the new will terminate the old and play itself), but what I want is to keep playing the old one even when the new one is played.

SoundPlayer wowSound = new SoundPlayer("soundEffect/Wow.wav");

SoundPlayer countingSound = new SoundPlayer("soundEffect/funny.wav");

wowSound.Play(); // play like background music

countingSound.Play();  // from click to generate the sound effect

Answer

Picrofo Software picture Picrofo Software · Dec 18, 2012

You may use SoundPlayer.PlaySync() which plays the .wav file using the User Interface thread so that wowSound would be played first. Then, countingSound will be played after wowSound has finished playing

Example

SoundPlayer wowSound = new SoundPlayer(@"soundEffect/Wow.wav"); //Initialize a new SoundPlayer of name wowSound
SoundPlayer countingSound = new SoundPlayer(@"soundEffect/funny.wav"); //Initialize a new SoundPlayer of name wowSound
wowSound.PlaySync(); //Play soundEffect/Wow.wav synchronously
countingSound.PlaySync();  //Play soundEffect/funny.wav synchronously 

NOTICE: You can not play more than ONE sound at the same time using SoundPlayer as it does not support playing simultaneous sounds. If you would like to play TWO or more sounds at once, System.Windows.Media.MediaPlayer would be a better option

Example

MediaPlayer wowSound = new MediaPlayer(); //Initialize a new instance of MediaPlayer of name wowSound
wowSound.Open(new Uri(@"soundEffect/Wow.wav")); //Open the file for a media playback
wowSound.Play(); //Play the media

MediaPlayer countingSound = new MediaPlayer(); //Initialize a new instance of MediaPlayer of name countingSound
countingSound.Open(new Uri(@"soundEffect/funny.wav")); //Open the file for a media playback
countingSound.Play(); //Play the media