473,573 Members | 2,806 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using PlaySound to play a resource with SND_RESOURCE

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(st ring audioRes)
{
// Get the resource into a stream
System.IO.Strea m str =
Assembly.GetExe cutingAssembly( ).GetManifestRe sourceStream("M yApp.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(st ring audioRes)
{
// Note: 'MyObject' is a class in the same EXE as the embedded WAV
IntPtr HINSTANCE = Marshal.GetHINS TANCE(MyObject. GetType().Modul e);
PlaySound("MyAp p.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.wa v").

Can anybody see anything wrong with my second code sample?

TIA
Jared

Aug 9 '06 #1
3 10620
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(st ring audioRes)
{
// Get the resource into a stream
System.IO.Strea m str =
Assembly.GetExe cutingAssembly( ).GetManifestRe sourceStream("M yApp.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.Queu eUserWorkItem(
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 QueueUserWorkIt em and then
cast it back to a byte array in the anonymous delegate.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"Jared" <go****@triplet reesoftware.com wrote in message
news:11******** **************@ m79g2000cwm.goo glegroups.com.. .
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(st ring audioRes)
{
// Get the resource into a stream
System.IO.Strea m str =
Assembly.GetExe cutingAssembly( ).GetManifestRe sourceStream("M yApp.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(st ring audioRes)
{
// Note: 'MyObject' is a class in the same EXE as the embedded WAV
IntPtr HINSTANCE = Marshal.GetHINS TANCE(MyObject. GetType().Modul e);
PlaySound("MyAp p.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.wa v").

Can anybody see anything wrong with my second code sample?

TIA
Jared

Aug 9 '06 #2
Thanks for your quick reply Nicholas. However, the code that works is
playing the WAV asynchronously. The code that doesn't work is NOT
playing it asynchronously, so I don't think GC is an issue. Btw, I've
tried the code below using both sync and async, to no avail.

In other words, the following code produces no sound, even though
HINSTANCE appears to be a valid hmod and my resource path points to the
embedded WAV:

IntPtr HINSTANCE = Marshal.GetHINS TANCE(MyObject. GetType().Modul e);
PlaySound("MyAp p.Media.MySound .wav", HINSTANCE, SND_SYNC |
SND_RESOURCE);

TIA
Jared


Nicholas Paldino [.NET/C# MVP] wrote:
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(st ring audioRes)
{
// Get the resource into a stream
System.IO.Strea m str =
Assembly.GetExe cutingAssembly( ).GetManifestRe sourceStream("M yApp.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.Queu eUserWorkItem(
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 QueueUserWorkIt em and then
cast it back to a byte array in the anonymous delegate.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"Jared" <go****@triplet reesoftware.com wrote in message
news:11******** **************@ m79g2000cwm.goo glegroups.com.. .
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(st ring audioRes)
{
// Get the resource into a stream
System.IO.Strea m str =
Assembly.GetExe cutingAssembly( ).GetManifestRe sourceStream("M yApp.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(st ring audioRes)
{
// Note: 'MyObject' is a class in the same EXE as the embedded WAV
IntPtr HINSTANCE = Marshal.GetHINS TANCE(MyObject. GetType().Modul e);
PlaySound("MyAp p.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.wa v").

Can anybody see anything wrong with my second code sample?

TIA
Jared
Aug 9 '06 #3
For those who are interested, I solved my original problem
(popping/clicking) by using a thread pool task for async playback as
Nicholas suggested. I couldn't get his example to compile, so the code
I ended up with is shown below (Win32 imports omitted).

Note: I believe the popping/clicking was somehow caused by the fact
that the sound is playing in response to input on the serial port from
a barcode scanner. Playing the sound directly from, say, a button
click or on a thread pool task seems to have eliminated the
popping/clicking.

private static void PlaySound(objec t bytes)
{
PlaySound((byte[])bytes, IntPtr.Zero, SND_MEMORY);
}

private static void PlayResource(st ring audioRes)
{
// Get the resource into a stream
System.IO.Strea m str =
Assembly.GetExe cutingAssembly( ).GetManifestRe sourceStream("M yApp.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 on a new thread
ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Pl aySound), bytes);
}

Nicholas Paldino [.NET/C# MVP] wrote:
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(st ring audioRes)
{
// Get the resource into a stream
System.IO.Strea m str =
Assembly.GetExe cutingAssembly( ).GetManifestRe sourceStream("M yApp.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.Queu eUserWorkItem(
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 QueueUserWorkIt em and then
cast it back to a byte array in the anonymous delegate.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"Jared" <go****@triplet reesoftware.com wrote in message
news:11******** **************@ m79g2000cwm.goo glegroups.com.. .
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(st ring audioRes)
{
// Get the resource into a stream
System.IO.Strea m str =
Assembly.GetExe cutingAssembly( ).GetManifestRe sourceStream("M yApp.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(st ring audioRes)
{
// Note: 'MyObject' is a class in the same EXE as the embedded WAV
IntPtr HINSTANCE = Marshal.GetHINS TANCE(MyObject. GetType().Modul e);
PlaySound("MyAp p.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.wa v").

Can anybody see anything wrong with my second code sample?

TIA
Jared
Aug 11 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2338
by: MLH | last post by:
I have a line of code that works when called from a procedure in Access 2.0 form... PlaySound("C:\cr\help\Help0018.wav", 0) I imported what I thought was needed into A97. However, running it is unsuccessful. I get an error saying "file mmsystem not found". I think I've violated some API call protocol.
0
231
by: CM | last post by:
There is a function called Playsound. But I think it can only play wav. I don't know how to use it in .net application to play MP3 or rm music. I am failed to find any sample code. Anyone can help? Thanks! CM
3
4635
by: Harry J. Smith | last post by:
I added some sounds to my application, but the example in the msdn Library did not work. It had: public static extern bool PlaySound( string szSound, IntPtr hMod, PlaySoundFlags flags ); The file coredll was not found. I changed it to and it now works. What is the best way to handle this? -Harry
4
4503
by: rcattral | last post by:
Has anybody been using the PlaySound() function to play WAV files from within a DLL? Here is what I normally do. Since upgrading to 7.1 NET after using VC 6.0 for quite some time, I found that I had to add the following lines in order to use the multimedia extensions. In stdafx.h #include <MMSystem.h>
2
1679
by: Joe Thompson | last post by:
Hi, I am trying to use PlaySound in a VC++.net Windows app (VS 2003). I can use it to play a file but now I want to play it from a resource. I have two questions: How do I add a wav file to my project as a resource (steps please) How do I call PlaySound once that I have the wav file as part of the resource.
10
2465
by: Ot | last post by:
I found information on PlaySound. I implemented it in my program and it works just dandy. The only little problem is that I have to package the ..wav files and send them along since PlaySound plays a sound file. One of the options I found in a nice description of PlaySound says that there are a couple of other choices. 1) The sound can...
9
11834
by: Andy | last post by:
Hi, I have an application that has several forms. Each form acts as a monitor of a gateway system. If the gateway appears to be dead, the application should play a .wav file (not resource) until the user clicks a button to acknowledge the situation. To keep things simple, lets assume there is only one monitor. If I use the old...
6
15933
by: David Veeneman | last post by:
How do I configure a .NET 2.0 SoundPlayer object to play a WAV file embedded as a resource? I have tried the example in the MSDN documentation, and I am getting nowhere. Is there a simple example of how to do this, or can someone provide an example? Thanks. David Veeneman Foresight Systems
0
1893
by: poppy | last post by:
I tried to play a wav file with function Playsound() but it played only the first seconds of the song.I would like to play whole the song.What might de be wrong?Here is my code in case someone can help. /* This uses the high level WAVE API PlaySound() to play a WAVE file in memory. I simply open the WAVE file called "nagelas.wav" (ie,...
0
7776
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7686
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8200
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7771
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5289
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3730
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3731
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2197
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1038
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.