C# Embed wave file

Here is a simple way to embed wav file or any other resource in a C# application. Just add the file and set it’s property “Build Action” to “Embedded Resource”. Then at run time extract the resource and use it in your application.

// this will show you all available resource
//string[] resNames = a.GetManifestResourceNames();

// extract the wav file
Stream mstrWaveFile = Assembly.GetExecutingAssembly().GetManifestResourceStream(WAVE_RESOURCE);
SoundPlayer player = new SoundPlayer(mstrWaveFile);
// and play it
player.Play();

2 Comments

  1. anelson says:

    I use this all the time, and I can’t believe I don’t read about it more often. I was doing some C++ GUI programming and REALLY missed the ability to easily embed stuff.

    I would note that this is a Stream object, and thus IDisposable. If you’re going to go crazy with resource streams, don’t forget your using statements, or Dispose() your streams in some other way.

    Also, you might note how these resources are named. It’s not just with the name of the file you’re embedding. Sometimes I forget how they’re named, and Lutz Roeder’s Resourcer comes to the rescue.

  2. orn says:

    That’s true I should have wrapped it with Using(

    Same for me I forget the conventions too, that’s why I left that dead code in there. You can activate and break point on the following line and it will show you the resources and what the naming looks like. If your name spaces are laid out properly is should be something like myspace.resourece.theresource

    //string[] resNames = a.GetManifestResourceNames();

Leave a Reply