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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With