Click here to Skip to main content
15,884,353 members
Articles / Programming Languages / C#
Article

Embedding and Playing WAV Audio Files in a WinForms Application

Rate me:
Please Sign up or sign in to vote.
4.70/5 (15 votes)
31 Jan 20074 min read 159.9K   4.5K   70   17
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

Introduction

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.

Image 1

Figure 1. Demonstration Form in Sample Application

Getting Started.

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.

Image 2

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".

Image 3

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.

Image 4

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".

Image 5

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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Media;

namespace PlayWavFiles
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

The sum total of code required is contained in three button click event handlers; the exit button is used to close the application:

private void btnExit_Click(object sender, EventArgs e)
{
    Application.Exit();
}

The next button click event handler plays an embedded WAV file once:

C#
private void btnDemo1_Click(object sender, EventArgs e)
{
    try
    {
        SoundPlayer sndplayr = new 
                 SoundPlayer(PlayWavFiles.Properties.Resources.BuzzingBee);
        sndplayr.Play();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message + ": " + ex.StackTrace.ToString(), 
                       "Error");
    }
}

The click event handler creates an instance of the System.Media sound player and sets the player to load an audio file from the application resources. After the resource is loaded into the player, the player's Play function is called and the audio file is played.

The next click event handler demonstrates looping the play of an embedded audio file:

C#
private void btnDemo2_Click(object sender, EventArgs e)
{
    try
    {
        SoundPlayer sndplayr = new 
            SoundPlayer(PlayWavFiles.Properties.Resources.LoopyMusic);
        if (btnDemo2.Text == "Demo WAV 2")
        {
            sndplayr.PlayLooping();
            btnDemo2.Text = "STOP";
        }
        else
        {
            sndplayr.Stop();
            btnDemo2.Text = "Demo WAV 2";
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message + ": " + ex.StackTrace.ToString(), 
            "Error");
    }
}

This example works in much the same way as the last click event handler except that this handler calls the sound player's "PlayLooping" function rather than the "Play" function; with this option called, the WAV file will play in a loop and will terminate only by playing another WAV file or by calling the sound player's "Stop" function. To support this, when the loop is started, the text of the button is changed to read, "STOP". If the user clicks on the button when it says "STOP" the player's "Stop" function is called and the button's text is restored to read, "Demo WAV 2". Subsequent clicks will start the loop playing or stop the player and update the text of the button to alternative between the two options.

That is all there is to the code used to support the play of embedded audio files.

Summary

The example provided shows how to embed audio files into an application's resources, and how to retrieve the file and play it using the System.Media class library. Similar functionality can obtained by importing and using the winmm.dll; however, the approach shown requires less code and is safer from the standpoint of deployment.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGood Pin
Hammad Kan26-Jun-12 19:35
Hammad Kan26-Jun-12 19:35 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey24-Apr-12 23:56
professionalManoj Kumar Choubey24-Apr-12 23:56 
Questionthankyou. Pin
swethaalampally18-Apr-12 19:18
swethaalampally18-Apr-12 19:18 
GeneralNice Job Pin
Don Driskell22-Jul-09 7:37
Don Driskell22-Jul-09 7:37 
QuestionGet Decibel value from wav file Pin
AngelaM21-Aug-08 0:04
AngelaM21-Aug-08 0:04 
QuestionPossible to set output device? Pin
KenNashua18-Jul-07 5:24
KenNashua18-Jul-07 5:24 
Is there any way for the SoundPlayer class to specify the output device in the case that there's multiple audio devices on a single system? Anyone have any sample code pointers that implement such a system?
GeneralResource management Pin
jmueller1-Feb-07 4:26
jmueller1-Feb-07 4:26 
GeneralRe: Resource management Pin
Patrick Etc.1-Feb-07 9:34
Patrick Etc.1-Feb-07 9:34 
GeneralRe: Resource management Pin
Ilíon2-Feb-07 4:17
Ilíon2-Feb-07 4:17 
GeneralRe: Resource management Pin
Patrick Etc.2-Feb-07 5:21
Patrick Etc.2-Feb-07 5:21 
GeneralRe: Resource management [modified] Pin
Ilíon2-Feb-07 6:54
Ilíon2-Feb-07 6:54 
GeneralRe: Resource management Pin
Patrick Etc.2-Feb-07 8:09
Patrick Etc.2-Feb-07 8:09 
GeneralRe: Resource management Pin
Ilíon2-Feb-07 8:24
Ilíon2-Feb-07 8:24 
GeneralI can't download this file! Pls check it! Pin
Nguyen Ba Tri31-Jan-07 13:48
Nguyen Ba Tri31-Jan-07 13:48 
GeneralRe: I can't download this file! Pls check it! Pin
Nguyen Ba Tri31-Jan-07 13:51
Nguyen Ba Tri31-Jan-07 13:51 
GeneralGreat Pin
Sacha Barber31-Jan-07 4:06
Sacha Barber31-Jan-07 4:06 
GeneralRe: Great Pin
Ilíon2-Feb-07 8:42
Ilíon2-Feb-07 8:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.