加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:56:01 所属栏目:百科 来源:网络整理
导读:我使用SoundPlayer在 WPF程序中播放声音效果.然而,我发现当两个声音效果同时播放时,新的声音效果将取代旧声音效果(即新声音将终止旧声音并播放自身),但我想要的是继续播放旧声音效果,即使新的一个播放. SoundPlayer wowSound = new SoundPlayer("soundEffect
我使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读