9

我用来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
4

3 回答 3

7

您可以使用SoundPlayer.PlaySync()which.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
于 2012-12-18T03:35:49.200 回答
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 的一个包装器......

于 2012-12-18T04:11:48.933 回答
0

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

http://naudio.codeplex.com/

它需要您编写更多代码,但是一旦您发现需求发生了变化(他们总是这样做)并且内置的媒体播放器将不再起作用,您会很高兴。

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

于 2012-12-18T09:45:23.677 回答