Play two sounds simultaneusly

AlanFoster picture AlanFoster · Jun 5, 2011 · Viewed 34.8k times · Source

Is there a way to play two sounds at the same time?

I know that SoundPlayer isn't able to do this. I can't use SoundEffect as I believe it's only part of XNA.

The two required sounds will be called at unknown and random times. The sound needs to be be controlled after it is played. i.e., the sound must be able to be stopped before it has finished playing.

Answer

JeremyWeir picture JeremyWeir · Jun 5, 2011

Reference PresentationCore and WindowsBase and try this...

var p1 = new System.Windows.Media.MediaPlayer();
p1.Open(new System.Uri(@"C:\windows\media\tada.wav"));
p1.Play();

// this sleep is here just so you can distinguish the two sounds playing simultaneously
System.Threading.Thread.Sleep(500);

var p2 = new System.Windows.Media.MediaPlayer();
p2.Open(new System.Uri(@"C:\windows\media\tada.wav"));
p2.Play();

EDIT I received a downvote probably because at first glance this looks like it will play the second sound after the first is finished. It doesn't, they are played by windows asynchronously. The sleep is there so if you test this code verbatim you can hear the sounds play together, it wouldn't be noticeable without the delay since they are the same sound.

This code demonstrates the two sounds playing on separate threads on top of each other, which is sort of pointless since the playback doesn't block anyway

new System.Threading.Thread(() => {
        var c = new System.Windows.Media.MediaPlayer();
        c.Open(new System.Uri(@"C:\windows\media\tada.wav"));
        c.Play();
    }).Start();

System.Threading.Thread.Sleep(500);

new System.Threading.Thread(() => {
        var c = new System.Windows.Media.MediaPlayer();
        c.Open(new System.Uri(@"C:\windows\media\tada.wav"));
        c.Play();
    }).Start();

http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer.stop.aspx The class also has the control you need to stop playback