SIGN UP MEMBER LOGIN:    
ARTICLE

Embedding and Playing WAV Audio Files in a Win Forms Application

Posted by Scott Lysle Articles | Windows Forms C# January 18, 2007
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.
Reader Level:
Download Files:
 

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.

Login to add your contents and source code to this article
share this article :
post comment
 

gfhgfhgfhgf

Posted by abhishek kumar Sep 12, 2011

Hello,

I am making an editor for the engine that will run both for Windows and xBox 360, I am using the XNA technology for the engine as it is the best for this stuff.  However, the editor does not require the use of the XNA technology. How do I load sound in the form, have a button that plays the sound, stop the sound and then save the sound in my own .bin file?

Let us say the sound.bin have two sound files stored in them, not just a little c:\location\sound.wav string that directs it to the sound, but the actual two sounds are stored in the file. How do you do that? And Using the reverse method of saving these sounds to load them and store them in the array, array[0]=holds sound 1, array[1]=holds sound 2, then using the function I would be able to play that sound, how do I do that? Can anyone help to the right direction how to achieve this? Thanks in advance.

Posted by Fahed Al Daye Jun 01, 2010

Hi, Can we play wav files whose path is included in an XML file? Or can we include the wav files in XML? Thank you

Posted by Bharathi Feb 07, 2007
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Gauge for SharePoint
Become a Sponsor