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

时间:2012-12-18 03:30:05

标签: 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

3 个答案:

答案 0 :(得分:6)

您可以使用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 

注意:您不能使用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

答案 1 :(得分:0)

using System.Threading.Tasks;

private void MyMethod()
{
    Task.Factory.StartNew(PlaySound1);
    Task.Factory.StartNew(PlaySound2);
}

private void PlaySound1()
{
    SoundPlayer wowSound = new SoundPlayer("soundEffect/Wow.wav");
    wowSound.Play();
}

private void PlaySound2()
{
    SoundPlayer countingSound = new SoundPlayer("soundEffect/funny.wav");
    countingSound.Play();
}

编辑:

Picrofo是对的,它不能以这种方式完成,但看起来你可以使用DirectShow .NET实现这一点,{{3}}只是MS DirectShow的包装...

答案 2 :(得分:0)

在WPF和C#中使用内置播放器一段时间之后,我发现它们功能太缺,所以我转而使用NAudio。

http://naudio.codeplex.com/

它要求你写一些代码,但是一旦你发现需求已经改变(他们总是这样做)并且内置媒体播放器将不再执行,你会很高兴。

源代码附带了一些示例,您可以在Stack Overflow上,codeplex网站上找到更多帮助,只需搜索Google即可。