开发者

How do I play two sounds one after the other in a Windows Forms application?

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.


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.


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();
  }


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();


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜