Play multiple sounds using SoundPlayer

using System.Windows.Media

Function void Play(string audioPath)
{
MediaPlayer myPlayer = new MediaPlayer();
myPlayer.Open(new System.Uri(audioPath));
myPlayer.Play();
}

Play(Application.StartupPath + "\\Track1.wav");
Play(Application.StartupPath + "\\Track2.wav");

This code could play two audio files simultaneously, the call in second audio track2.wav will not disturb the play of track1.wav .


You'll need to use DirectX (DirectSound) or some similar API that is designed to allow the playing of multiple sounds at the same time.


You could do this:

SoundPlayer supports WAV Stream. You could

  • MIX samples you play 'by-hand' and,
  • Fake (get the WAV header from somewhere, it's not complicated).

And provide such stream as a parameter to the SoundPlayer constructor.

That way you won't have to use somehow complicated DirectSound libraries, and still have mixing (multiple sounds at once).


There is one simple way to play multiple sounds at once in C# or VB.Net. You will have to call the mciSendString() API Function to play each .wav file. You won't even have to do multi-threading, unless you are loop-playing. Here is a complete working example of a MusicPlayer class created using mciSendString().

// Sound api functions
[DllImport("winmm.dll")]
static extern Int32 mciSendString(string command, StringBuilder buffer, int bufferSize, IntPtr hwndCallback);

In the above function, the key is first parameter command. As long as you call two functions with a separate command name, they will play separately/simultaneously. This is what I did in one of my C# programs:

private void PlayWorker()
{
    StringBuilder sb = new StringBuilder();
    mciSendString("open \"" + FileName + "\" alias " + this.TrackName, sb, 0, IntPtr.Zero);
    mciSendString("play " + this.TrackName, sb, 0, IntPtr.Zero);
    IsBeingPlayed = true;
}

EDIT: Added link to a working example.

Tags:

C#

.Net

Audio

Wav