This article describes an approach to embedding WAV audio files into an application and playing them through the use of the System.Media class library. Due to the use of the System.Media class library, this example does not rely upon the import of the "winmm.dll" in order to play the audio file and for that reason this approach requires far less code to implement. The audio files used were embedded into the application as resources which eliminates the need to package up external WAV files for installations requiring the presentation of audio files. At the same time, the use of embedded resources precludes the potential for such files being moved or deleted after the consuming application has been installed.
The solution provided with this download contains a single project entitled, "PlayWavFiles". The project is described in the solution explorer (figure 2). The project contains only the default references for a win forms application; the resources indicated were embedded into the application Resources and are not delivered with the application through an installation.
Figure 2. Solution Explorer
The example was written using Visual Studio 2005 using C#; open the solution into the IDE to examine the code.
Adding Audio Files the Resources
To add audio files to the solution, open the Resources.resx file shown in the solution explorer. Once open, you will see a combo box (figure 3) that is used to allow you to select the type of resource to add to the project, select the Audio file option from the list and then click on "Add Resource".
Figure 3. Adding Audio Files to Resources
Once you have selected the "Add Resource" button, a file browser will open and you can use this file browser to search for audio files and add them to the application resources.
Figure 4. Browsing for Audio Files
Once the audio files have been added to the application resources, select each item added and set the "Persistence" property to "Embedded in .resx".
Figure 5. Setting the Persistence Property for Added Audio Files
At this point, the audio files are added and set; they may now be used within the project.
The Code: Main Form.
There is only a single form in the application (
frmMain) and that form contains all of the code necessary to play the embedded audio files. Aside from the default imports, the
System.Media class library has been added to the form: