TIP: Playing a WAV File with C# 2.0

Playing a WAV file in C# can be exceedingly simple, thanks to the addition of the SoundPlayer within the .NET Framework. The SoundPlayer class is available in the System.Media namespace.

To play a WAV file, you only need to create a SoundPlayer, add the location of the WAV file, and then play the file. This takes all of three lines of code:

System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer();
myPlayer.SoundLocation = @"c:\click.wav";
myPlayer.Play();

With these three lines of code, the click.wav file would be loaded and played. If you'd like the sound to loop, you can use the PlayLooping() method instead of the Play() method.

With the ease with which WAV files can be played, you can see that you can quickly add sound effects to your applications. At the first click of a button, you can have a nose occur, or when a user types in text. You simply need to privide WAV files and capture the appropriate events.

I've included a super simple example with a rather crude WAV file sound so you can get the idea. This example has three buttons. The first simply plays a WAV file. The second plays a WAV file in a continuous loop (until you click another button or end the program). The third button plays a WAV file before doing something. In this case, the something is simply updating the time on the form. The code for this is below and requires the two WAV files called simple.wav and click.wav; they are included in the download file.

As you can see, this is not rocket science. This tip, however, barely scratches the surface of what you can do with WAV files and the Media classes.

The PlayWav program. (Note that most of this code is Windows Forms code generated by the IDE):

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

namespace WavPlayer
{
   public class Form1 : Form
   {
      /// <summary>
      /// Required method for Designer support -- do not modify
      /// the contents of this method with the code editor.
      /// </summary>
      private void InitializeComponent()
      {
         this.button1 = new System.Windows.Forms.Button();
         this.button2 = new System.Windows.Forms.Button();
         this.button3 = new System.Windows.Forms.Button();
         this.label1  = new System.Windows.Forms.Label();
         this.SuspendLayout();
         //
         // button1
         //
         this.button1.Location = new System.Drawing.Point(39, 25);
         this.button1.Name = "button1";
         this.button1.Size = new System.Drawing.Size(221, 46);
         this.button1.TabIndex = 0;
         this.button1.Text = "Simply Play WAV";
         this.button1.UseVisualStyleBackColor = true;
         this.button1.Click +=
            new System.EventHandler(this.button1_Click);
         //
         // button2
         //
         this.button2.Location = new System.Drawing.Point(39, 89);
         this.button2.Name = "button2";
         this.button2.Size = new System.Drawing.Size(221, 46);
         this.button2.TabIndex = 1;
         this.button2.Text = "Loop WAV";
         this.button2.UseVisualStyleBackColor = true;
         this.button2.Click +=
            new System.EventHandler(this.button2_Click);
         //
         // button3
         //
         this.button3.Location = new System.Drawing.Point(39, 153);
         this.button3.Name = "button3";
         this.button3.Size = new System.Drawing.Size(221, 46);
         this.button3.TabIndex = 2;
         this.button3.Text = "Click Sound";
         this.button3.UseVisualStyleBackColor = true;
         this.button3.Click +=
            new System.EventHandler(this.button3_Click);
         //
         // label1
         //
         this.label1.AutoSize = true;
         this.label1.Location = new System.Drawing.Point(36, 212);
         this.label1.Name = "label1";
         this.label1.Size = new System.Drawing.Size(35, 13);
         this.label1.TabIndex = 3;
         this.label1.Text = "label1";
         //
         // Form1
         //
         this.AutoScaleDimensions =
            new System.Drawing.SizeF(6F, 13F);
         this.AutoScaleMode =
            System.Windows.Forms.AutoScaleMode.Font;
         this.ClientSize = new System.Drawing.Size(292, 266);
         this.Controls.Add(this.label1);
         this.Controls.Add(this.button3);
         this.Controls.Add(this.button2);
         this.Controls.Add(this.button1);
         this.Name = "Form1";
         this.Text = "Form1";
         this.ResumeLayout(false);
         this.PerformLayout();
      }

      private System.Windows.Forms.Button button1;
      private System.Windows.Forms.Button button2;
      private System.Windows.Forms.Button button3;
      private System.Windows.Forms.Label label1;

      //********************************
      //***** Real code starts here ****
      //********************************

      private System.Media.SoundPlayer myPlayer;

      public Form1()
      {
         InitializeComponent();
         // create a player to be used in the application
         myPlayer = new System.Media.SoundPlayer();
      }

      private void button1_Click(object sender, EventArgs e)
      {
         myPlayer.SoundLocation = @"c:\simple.wav";
         myPlayer.Play();
      }

      private void button2_Click(object sender, EventArgs e)
      {
         myPlayer.SoundLocation = @"c:\simple.wav";
         myPlayer.PlayLooping();
      }

      private void button3_Click(object sender, EventArgs e)
      {
         myPlayer.SoundLocation = @"c:\click.wav";
         myPlayer.Play();
         label1.Text = "Doing something...." +
            System.DateTime.Now.ToLongTimeString();
      }

      [STAThread]
      static void Main()
      {
         Application.Run(new Form1());
      }
   }
}


About the Author

Bradley Jones

Bradley Jones, in addition to managing CodeGuru, Brad! oversees the Developer.com Newtwork of sites including Codeguru, Developer.com, DevX, VBForums, and over a dozen more with a focus on software development and database technologies. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days, Web 2.0 Heroes, and Windows Live Essentials and Services.
Google+ Profile | Linked-In Profile | Facebook Page

Downloads

Comments

  • Playing it twice

    Posted by ml23 on 03/03/2010 10:29am

    I have implemented the code with no problems but I am interested in having a single sound play twice. If one simply uses the Play() method twice, it only plays once and using the loop method, I have not figured out anyway to determine how many times it has played in order to call Stop() at the appropriate time.

    • title

      Posted by jorge on 07/03/2012 09:39pm

      Try calling PlaySync() twice.

      Reply
    Reply
  • Thanks!

    Posted by Nate SHoffner on 07/14/2009 02:20am

    Very simple. Other methods I've seen involve using P/Invoke, which is just stupid to me.

    Reply
  • Thank you!

    Posted by DrJBN on 08/07/2008 06:52pm

    This bit of code solved an enormous headache for me & was exactly what I needed. Great layout and I appreciate that you put it out.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Hurricane Sandy was one of the most destructive natural disasters that the United States has ever experienced. Read this success story to learn how Datto protected its partners and their customers with proactive business continuity planning, heroic employee efforts, and the right mix of technology and support. With storm surges over 12 feet, winds that exceeded 90 mph, and a diameter spanning more than 900 miles, Sandy resulted in power outages to approximately 7.5 million people, and caused an estimated $50 …

  • Download the Information Governance Survey Benchmark Report to gain insights that can help you further establish business value in your Records and Information Management (RIM) program and across your entire organization. Discover how your peers in the industry are dealing with this evolving information lifecycle management environment and uncover key insights such as: 87% of organizations surveyed have a RIM program in place 8% measure compliance 64% cannot get employees to "let go" of information for …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds