Jared,
My guess is that the problem is due to you calling PlaySound with the
SND_ASYNC. This will cause PlaySound to play the sound on another thread,
instead of the executing one. The function then immediately returns, and
then your function exists, making the byte array eligible for GC.
If you want to play the sound asynchronously, I would recommend creating
a thread pool task and executing that (or another thread if your thread pool
is pretty full already) like so:
private static void PlayResource(string audioRes)
{
// Get the resource into a stream
System.IO.Stream str =
Assembly.GetExecutingAssembly().GetManifestResourc eStream("MyApp.Media."
+ audioRes);
if(null == str) return;
// Bring stream into a byte array
byte[] bytes = new Byte[str.Length];
str.Read(bytes, 0, (int)str.Length);
// Play the resource. Execute the code on a thread pool thread.
ThreadPool.QueueUserWorkItem(
delegate(object state)
{
// Play the sound.
PlaySound(bytes, IntPtr.Zero, SND_MEMORY);
// Get out.
return;
}, null);
}
This should work, and keep the bytes referenced alive. If not, then you
can just pass bytes as the state parameter to QueueUserWorkItem and then
cast it back to a byte array in the anonymous delegate.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
mvp@spam.guard.caspershouse.com
"Jared" <google@tripletreesoftware.comwrote in message
news:1155150435.509830.306250@m79g2000cwm.googlegr oups.com...
Quote:
I'm using the first code sample below to play WAV files stored as
embedded resources. For some reason I *occasionally* get scratching
and crackling. I'm using a couple WAVs that ship with Windows, and
they play fine outside of my app.
>
This code works, but has the random "scratching" problem:
>
private static void PlayResource(string audioRes)
{
// Get the resource into a stream
System.IO.Stream str =
Assembly.GetExecutingAssembly().GetManifestResourc eStream("MyApp.Media."
+ audioRes);
if(null == str) return;
>
// Bring stream into a byte array
byte[] bytes = new Byte[str.Length];
str.Read(bytes, 0, (int)str.Length);
>
// Play the resource
PlaySound(bytes, IntPtr.Zero, SND_ASYNC | SND_MEMORY);
}
>
I'd like to try playing the resource WAVs directly, but I get no sound
with the following revised code:
>
private static void PlayResource(string audioRes)
{
// Note: 'MyObject' is a class in the same EXE as the embedded WAV
IntPtr HINSTANCE = Marshal.GetHINSTANCE(MyObject.GetType().Module);
PlaySound("MyApp.Media." + audioRes, HINSTANCE, SND_RESOURCE);
}
>
I suspect it has something to do with the way I'm specifying the
resource path, but the documentation on this is suspiciously absent.
I'm passing the same param value to both versions of my PlayResource()
method, and the param is the filename with extension (i.e.
"MySound.wav").
>
Can anybody see anything wrong with my second code sample?
>
TIA
Jared
>