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:
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!
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.