Here's a deceptively simple question:
What is the proper way to asynchronously play an embedded .wav resource file in Windows Forms?
Attempt #1:
var player = new SoundPlayer();
player.Stream = Resources.ResourceManager.GetStream("mySound");
player.Play(); // Note that Play is asynchronous
Attempt #2:
using (var audioMemory = Resources.ResourceManager.GetStream("mySound"))
{
using (var player = new SoundPlayer(audioMemory))
{
player.Play();
}
}
Attempt #3:
using (var audioMemory = Resources.ResourceManager.GetStream("mySound"))
{
using (var player = new SoundPlayer(audioMemory))
{
player.PlaySync();
}
}
Attempt #4:
ThreadPool.QueueUserWorkItem(ignoredState =>
{
using (var audioMemory = Resources.ResourceManager.GetStream("mySound"))
{
using (var player = new SoundPlayer(audioMemory))
{
player.PlaySync();
}
}
});
It seems like SoundPlayer should have a PlayAsyncCompleted event. Unfortunately, no such event exists. Am I missing something? What's the proper way to asynchronously play a .wav embedded resource in Windows Forms?
I don't have enough reputation to comment so I'll just answer.
If your requirements to play sound are "deceptively simple" (you just want to play the occasional sound when a single winform user does something) then I would use Attempt #4 above.
Larry Osterman's "what's wrong with this code part 26" has his "system" spin off a new threadpool thread (to play sound) with each keystroke. He indicates than hammering away on it saturated the default 500 thread pool size in about 15 seconds of typing but this was also with a client/server app using async RPC that were also using the threadpool. Really not a "deceptively simple" application.
If you are trying to queue sound bytes every second (or faster) for 10s or 100s of seconds at a time then its really not a "simple application" and a queued threading/priority subsystem would probably be in order.
I still use the good ol' waveOut____ functions from the win32 API. Here's a good code sample:
http://www.codeproject.com/KB/audio-video/cswavplay.aspx
Edit: a much simpler solution to your problem is to extract the embedded resource, save it as a real file somewhere, and then use SoundPlayer to play the file. A little clunky, but simple and you won't have the resource disposal problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With