2012-12-18 38 views
6

我使用SoundPlayer在WPF程序中播放声音效果。但是,我发现当两个声音效果同时播放时,新声音会替换旧声音(即新声音会终止旧声音并自我演奏),但我想要的是在播放旧声音时新的播放。如何用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 
+0

http://www.interact-sw.co.uk/iangblog/2008/01/25/wpf-concurrent-audio ..我看到这一个,但没有尝试.. – Mullaly

+0

这是因为你喜欢派对? – WildCrustacean

回答

4

您可以使用SoundPlayer.PlaySync()起着使用用户界面线程,这样wowSound将首先播放的.wav文件。然后,countingSoundwowSound后播放播放完毕

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

我试过PlaySync()方法,但是我发现新的只是在老的之后播放。我想同时玩两个。您可能认为wowSound.Play()播放的是背景音乐,countingSound.Play()是通过点击播放的。 –

+0

@Alanlau如果你想同时播放这两种声音,我认为你可以尝试'播放()'。祝你有美好的一天:) –

+0

Picrofo,我希望一个不错的,但我发现Play()方法将让新的替换旧的。换句话说,新的将终止旧的自我发挥。 –

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这只是一个包装的MS DirectShow ...

+0

即使你尝试运行一个新的'Thread'来播放波形文件,我也不认为这会起作用。 'SoundPlayer'使用Native WINAPI函数来播放不幸不支持播放同步声音的波形文件。祝你今天愉快 :) –

0

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

http://naudio.codeplex.com/

它要求你写多一点的代码,但一旦你发现需求发生了变化(他们总是这样)和内置的媒体播放器不会做了,那么你会很高兴。

源代码附带了一些示例,您可以在Code Stack站点上的Stack Overflow以及搜索Google上找到更多帮助。