Click here to Skip to main content
Click here to Skip to main content

Embedding and Playing WAV Audio Files in a WinForms Application

, 31 Jan 2007
Rate this:
Please Sign up or sign in to vote.
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.

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.

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:

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:

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:

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

Share

About the Author

salysle
Software Developer (Senior)
United States United States
No Biography provided

Comments and Discussions

 
QuestionGood PinmemberHammad Kan26-Jun-12 19:35 
GeneralMy vote of 5 Pinmembermanoj kumar choubey24-Apr-12 23:56 
Questionthankyou. Pinmemberswethaalampally18-Apr-12 19:18 
GeneralNice Job PinmemberDonDriskell22-Jul-09 7:37 
QuestionGet Decibel value from wav file PinmemberNiyaHere21-Aug-08 0:04 
QuestionPossible to set output device? PinmemberKenNashua18-Jul-07 5:24 
GeneralResource management Pinmemberjmueller1-Feb-07 4:26 
GeneralRe: Resource management PinmemberPatrick Sears1-Feb-07 9:34 
GeneralRe: Resource management PinmemberIlíon2-Feb-07 4:17 
GeneralRe: Resource management PinmemberPatrick Sears2-Feb-07 5:21 
GeneralRe: Resource management [modified] PinmemberIlíon2-Feb-07 6:54 
GeneralRe: Resource management PinmemberPatrick Sears2-Feb-07 8:09 
GeneralRe: Resource management PinmemberIlíon2-Feb-07 8:24 
GeneralI can't download this file! Pls check it! PinmemberNguyen Ba Tri31-Jan-07 13:48 
GeneralRe: I can't download this file! Pls check it! PinmemberNguyen Ba Tri31-Jan-07 13:51 
GeneralGreat PinmemberSacha Barber31-Jan-07 4:06 
GeneralRe: Great PinmemberIlíon2-Feb-07 8:42 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.141015.1 | Last Updated 31 Jan 2007
Article Copyright 2007 by salysle
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid