如何在不暂停程序的情况下在c#/ wpf中播放声音。 [英] How to play sounds in c#/wpf without pausing the program.
问题描述
嘿那里,
i需要在我的wpf项目中的KeyDown事件上播放一些声音。
i已经尝试过System.Media.SoundPlayer();
使用soundPlayer的
thie prolem是当声音播放时,程序暂停。
声音仅约0.2秒,但它仍然会产生很大的差异。它会影响应用程序的性能。
和声音是.wav文件,如果需要我可以将它转换为mp3。
。 : - )
我尝试过:
我已经尝试了 -
System.Media.SoundPlayer();
Hey there,
i need to play some sounds on KeyDown event in my wpf project.
i have already tried System.Media.SoundPlayer();
thie prolem with the soundPlayer is that when the sound plays , the program gets paused.
The sounds are of just about 0.2 sec, but it still creates a big difference. It affects the performance of the application.
and the sounds are .wav files, if needed i can convert it to mp3.
thenks. :-)
What I have tried:
I have already tried-
System.Media.SoundPlayer();
推荐答案
系统。 Media.SoundPlayer
能够异步播放声音,因此不会阻止UI线程;使用LoadAsync
加载文件,LoadCompleted
以获取有关加载完成的信息,并播放
播放它:
System.Media.SoundPlayer
is capable of playing sounds asynchronously so it doesn't block the UI thread; useLoadAsync
to load the file,LoadCompleted
to get informed about the load completion, andPlay
to play it:
SoundPlayer player = new SoundPlayer("file.wav");
player.LoadCompleted += delegate(object sender, AsyncCompletedEventArgs e) {
player.Play();
};
player.LoadAsync();
或者,如果除了玩游戏之外你不需要做任何其他事情,你可以打电话给在调用构造函数后立即播放
- 感谢Richard Deeming指出这一点!
Or, if you don't need to do anything else after the loading aside from playing, you can just call Play
immediately after calling the constructor - thanks to Richard Deeming for pointing this out!
SoundPlayer player = new SoundPlayer("file.wav");
player.Play();
此外,如果您多次播放相同的声音(您可能会这样做,因为您在KeyDown上播放它们)事件),重新使用SoundPlayer对象是值得的,所以你不必创建它们并一遍又一遍地加载声音。
Additionally, if you're playing the same sound multiple times (which you probably do, given that you play them on KeyDown events), it's worth to re-use the SoundPlayer objects so you don't have to create them and load the sound over and over again.
这篇关于如何在不暂停程序的情况下在c#/ wpf中播放声音。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!