Click here to Skip to main content
15,912,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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();
Posted

1 solution

System.Media.SoundPlayer is capable of playing sounds asynchronously so it doesn't block the UI thread; use LoadAsync to load the file, LoadCompleted to get informed about the load completion, and Play to play it:
C#
SoundPlayer player = new SoundPlayer("file.wav");
player.LoadCompleted += delegate(object sender, AsyncCompletedEventArgs e) {
    player.Play();
};
player.LoadAsync();

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!
C#
SoundPlayer player = new SoundPlayer("file.wav");
player.Play();

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.
 
Share this answer
 
v3
Comments
Richard Deeming 10-Feb-16 12:09pm    
According to the documentation[^], the Play method will take care of loading the file for you if it hasn't already been loaded, so your code can be simplified to:

SoundPlayer player = new SoundPlayer("file.wav");
player.Play();


If the OP is playing the same sound multiple times, it would be worth using the same SoundPlayer instance each time, so that the file only has to be loaded once.
Thomas Daniels 10-Feb-16 12:30pm    
Good points, thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900