c# - WPF如何同时播放两个声音文件?

标签 c# wpf pixelsense

我在WPF程序中使用SoundPlayer播放音效。但是,我发现当两个音效同时播放时,新的会取代旧的(即新的会终止旧的并自己播放),但我想要的是继续播放旧的即使播放新的。

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

最佳答案

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

关于c# - WPF如何同时播放两个声音文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13925840/

相关文章:

WPF:重置 scatterviewitems 的位置?

c# - 实现平衡二叉搜索树?

c# - 了解 .NET Framework 中哪些方法返回 null 的简单方法

c# - 在WPF中将View作为命令参数传递。紫罗兰色MVVM方法吗?

delphi - 如何在 Delphi 中为 Microsoft Surface Pen 编程?

c# - MS Surface Tag Visualizer 窃取接触事件

c# - 没有服务定位器的 IFilterProvider 注入(inject)

c# - 返回唯一值而不删除重复项 - C#

c# - ScrollViewer 本身的垂直偏移量与 PropertyChangedEventArgs 的垂直偏移量有什么区别

wpf - 来自另一个线程的 GUI 更新 - WPF Powershell