5

I want to play two sounds one after the other in reaction to a button click. When the first sound finishes, the second sound should start playing.

My problem is that every time the button is clicked these two sounds are different and I don't know their lengths in order to use Thread.Sleep. But I don't want these sounds to play on top of each other.

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
hamze
  • 7,061
  • 6
  • 34
  • 43
  • i saw this but not helped. http://stackoverflow.com/questions/6240002/play-two-sounds-simultaneusly – hamze Oct 16 '11 at 14:13

4 Answers4

8

Sounds like you're after the PlaySync method of SoundPlayer class.. first add this on top:

using System.Media;

Then have such code:

SoundPlayer player = new SoundPlayer(@"path to first media file");
player.PlaySync();

player = new SoundPlayer(@"path to second media file");
player.PlaySync();

This class is available since .NET 2.0 so you should have it.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
1

The MediaPlayer has MediaEnded event. In the event handler, just start the new media and they should play back to back.

protected System.Windows.Media.MediaPlayer pl = new MediaPlayer();

public void StartPlayback(){
  pl.Open(new Uri(@"/Path/to/media/file.wav"));
  pl.MediaEnded += PlayNext;
  pl.Play();
  }

private void PlayNext(object sender, EventArgs e){
  pl.Open(new Uri(@"/Path/to/media/file.wav"));
  pl.Play();
  }
Darcara
  • 1,598
  • 1
  • 13
  • 33
1

In Shadow Wizards example, it's not necessary to make a new soundplayer each time. This also works:

player.SoundLocation = "path/to/media";
player.PlaySync();
player.SoundLocation = "path/to/media2";
player.PlaySync();
e-motiv
  • 5,795
  • 5
  • 27
  • 28
0

Example Using NAudio

private List<string> wavlist = new List<string>();
wavlist.Add("c:\\1.wav");
wavlist.Add("c:\\2.wav");
foreach(string file  in wavlist)
{
          AudioFileReader audio = new AudioFileReader(file);
          audio.Volume = 1;
          IWavePlayer player = new WaveOut(WaveCallbackInfo.FunctionCallback());
          player.Init(audio);
          player.Play();
          System.Threading.Thread.Sleep(audio.TotalTime);
          player.Stop();
          player.Dispose();
          audio.Dispose();
          player = null;
          audio = null;
 }