How to play two sounds one by one in a Windows Forms application?

I want to play two sounds one by one in response to a button press. When the first sound ends, the second sound should begin.

My problem is that every time the button is clicked, the two sounds are different, and I don’t know their length to use Thread.Sleep . But I do not want these sounds to play on each other.

+4
source share
4 answers

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

 using System.Media; 

Then we get the following 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 with .NET 2.0, so you must have one.

+5
source

There is a MediaEnded event in MediaPlayer. In the event handler, just start the new medium and they should play 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(); } 
+1
source

In the Shadow Wizards example, there is no need to create a new sound player each time. This also works:

 player.SoundLocation = "path/to/media"; player.PlaySync(); player.SoundLocation = "path/to/media2"; player.PlaySync(); 
+1
source

NAudio example

 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; } 
0
source

All Articles