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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/csharp/100000.html

猜你在找的C#相关文章