Home > C# > Visual C# Note: Embed Wave File in .Net Application

Visual C# Note: Embed Wave File in .Net Application

When writing small-scale applications, I think it’s good practice to embed resources, such as images, sound waves, and icons, in the application. This way you don’t need to worry about remembering to add separate files when you distribute your applications — a single .exe file is all you need.

I just finished a small project (“Tetris”) that utilized embedded wave files. Using an embedded wave file involves two steps. The first step, off course, is to “embed” the wave file in the application. This is actually is very easy. With you project open in Visual Studio 2005, simply drag your wave file and drop it in your project in the “Solution Explorer”. Then set “Build Action” to “Embedded Resource”, see Figure 1. When you build the project next time, the wave file will be embedded in the application.

Wave File Properties
Figure 1. To embed a file, set “Build Action” to “Embedded Resource”.

The second step is to access the wave file when you need to play it. You need to create a stream and associate your embedded wave file to the stream. Then you can use a SoundPlayer object to read from this stream and play the embedded wave file. Below are the codes to play my embedded wave file. Note that when you access the embedded wave file, you have to use format “Namespace.WaveFileName”. In my case, the namespace is “Tetris” and the wave file name is “Tetris.wav”. Therefore I have to use “Tetris.Tetris.wav” to access it.


using System.media;
using System.Reflection;
// Open the embedded wave file using a SoundPlayer object
Assembly asm = Assembly.GetExecutingAssembly();
Stream sm = asm.GetManifestResourceStream("Tetris.Tetris.wav");
// Play embedded wave file
sPlayer = new SoundPlayer(sm);
sPlayer.Play();

Categories: C# Tags:
  1. No comments yet.
  1. No trackbacks yet.