Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 810
hamze Avatar asked Oct 16 '11 14:10

hamze


3 Answers

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.

like image 84
Shadow Wizard Hates Omicron Avatar answered Nov 12 '22 11:11

Shadow Wizard Hates Omicron


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();
  }
like image 21
Darcara Avatar answered Nov 12 '22 09:11

Darcara


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();
like image 1
e-motiv Avatar answered Nov 12 '22 10:11

e-motiv