微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我使用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

解决方法

您可以使用Soundplayer.PlaySync()使用用户界面线程播放.wav文件,以便首先播放wowSound.然后,在wowSound完成播放后将播放countingSound

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

原文地址:https://www.jb51.cc/csharp/100000.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐