如何用WPF同时播放两个声音文件?

Ala*_*lau 9 c# wpf pixelsense

我用来SoundPlayer在WPF程序中播放声音效果.然而,我发现当两个声音效果同时播放时,新的声音效果将取代旧声音效果(即新声音将终止旧声音并播放自身),但我想要的是继续播放旧声音效果,即使新的一个播放.

SoundPlayer wowSound = new SoundPlayer("soundEffect/Wow.wav");

SoundPlayer countingSound = new SoundPlayer("soundEffect/funny.wav");

wowSound.Play(); // play like background music

countingSound.Play();  // from click to generate the sound effect
Run Code Online (Sandbox Code Playgroud)

Pic*_*are 7

您可以使用SoundPlayer.PlaySync()哪个播放.wav文件使用用户界面线程,以便wowSound首先播放.然后,countingSound将被打后wowSound播放完毕

SoundPlayer wowSound = new SoundPlayer(@"soundEffect/Wow.wav"); //Initialize a new SoundPlayer of name wowSound
SoundPlayer countingSound = new SoundPlayer(@"soundEffect/funny.wav"); //Initialize a new SoundPlayer of name wowSound
wowSound.PlaySync(); //Play soundEffect/Wow.wav synchronously
countingSound.PlaySync();  //Play soundEffect/funny.wav synchronously 
Run Code Online (Sandbox Code Playgroud)

注意:您不能同时播放多个声音,SoundPlayer因为它不支持播放同步声音.如果您想一次播放两个或更多声音,那System.Windows.Media.MediaPlayer将是更好的选择

MediaPlayer wowSound = new MediaPlayer(); //Initialize a new instance of MediaPlayer of name wowSound
wowSound.Open(new Uri(@"soundEffect/Wow.wav")); //Open the file for a media playback
wowSound.Play(); //Play the media

MediaPlayer countingSound = new MediaPlayer(); //Initialize a new instance of MediaPlayer of name countingSound
countingSound.Open(new Uri(@"soundEffect/funny.wav")); //Open the file for a media playback
countingSound.Play(); //Play the media
Run Code Online (Sandbox Code Playgroud)