A Simple C# Class to Play .WAV Files in .NET

WavPlay

This is a simple program to test a class I wrote when I needed to play some .wav files from C#. It uses the simple Win32 command PlaySound—a throwback to earlier programming days, but it works. There are only two commands, play and stop, which are really all you need a lot of times. I wrapped it all in a simple class including the defines needed for the Play method. There is not much more to this other than it works on Win2K and WinXP and is simple to use.

One other interesting thing is I used the OpenFileDialog, a pre-configured dialog box, to get a .wav file path. It is very simple to use. Just drag it from the Toolbox to your dialog box. Watch out for the "Filter" property. The documentation says:

For each filtering option, the filter string contains a description of the filter, followed by the vertical bar (|) and the filter pattern. The strings for different filtering options are separated by the vertical bar.

The following is an example of a filter string: "Text files (*.txt)|*.txt|All files (*.*)|*.*"

You can add serveral filter patterns to a filter by separating the file types with smicolons. For example: "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"

It's fairly easy to understand, but watch out for spaces, and that the '|' is used in two ways: to denote the actual search string extension, and to separate different search types. The dialog has several interesting functions as well. Have fun.

Bill

public class WAVSounds
{
  [DllImport("WinMM.dll")]
  public static extern bool  PlaySound(byte[]wfname, int fuSound);

  //  flag values for SoundFlags argument on PlaySound
  public int SND_SYNC       = 0x0000;      // play synchronously
                                           // (default)
  public int SND_ASYNC      = 0x0001;      // play asynchronously
  public int SND_NODEFAULT  = 0x0002;      // silence (!default)
                                           // if sound not found
  public int SND_MEMORY     = 0x0004;      // pszSound points to
                                           // a memory file
  public int SND_LOOP       = 0x0008;      // loop the sound until
                                           // next sndPlaySound
  public int SND_NOSTOP     = 0x0010;      // don't stop any
                                           // currently playing
                                           // sound

  public int SND_NOWAIT      = 0x00002000; // don't wait if the
                                           // driver is busy
  public int SND_ALIAS       = 0x00010000; // name is a Registry
                                           // alias
  public int SND_ALIAS_ID    = 0x00110000; // alias is a predefined
                                           // ID
  public int SND_FILENAME    = 0x00020000; // name is file name
  public int SND_RESOURCE    = 0x00040004; // name is resource name
                                           // or atom
  public int SND_PURGE       = 0x0040;     // purge non-static
                                           // events for task
  public int SND_APPLICATION = 0x0080;     // look for application-
                                           // specific association

//-----------------------------------------------------------------
public void Play(string wfname,int SoundFlags)
{
  byte[] bname = new Byte[256];    //Max path length
  bname = System.Text.Encoding.ASCII.GetBytes(wfname);
  PlaySound(bname,SoundFlags);
}
//-----------------------------------------------------------------
public void StopPlay()
{
  PlaySound(null,SND_PURGE);
}
//-----------------------------------------------------------------
}   //End WAVSounds class
//-----------------------------------------------------------------

    public Form1()
    {

      // Required for Windows Form Designer support
      //
      InitializeComponent();

      //
      // TODO: Add any constructor code after InitializeComponent
      // call
      //
        openFileDialog1.Title = "Select a Wave Sound File";
        openFileDialog1.Filter = "Wav Files(*.wav)|*.wav|
                                  All Files(*.*)|*.*";
    }
//-----------------------------------------------------------------
private void FindFileButton_Click(object sender, System.EventArgs e)
{
  openFileDialog1.FileName = m_wav_file.Text;
  openFileDialog1.ShowDialog();
  m_wav_file.Text = openFileDialog1.FileName;
}
//-----------------------------------------------------------------
private void OnPlayButtonClick(object sender, System.EventArgs e)
{
  WAVSounds ws = new WAVSounds();
  ws.Play(m_wav_file.Text,ws.SND_ASYNC);
}
//-----------------------------------------------------------------
private void StopButton_Click(object sender, System.EventArgs e)
{
  WAVSounds ws = new WAVSounds();
  ws.StopPlay();
}
//-----------------------------------------------------------------

Downloads

Download demo project - 106 Kb
Download source - 3 Kb


Comments

  • i did not make it work :s

    Posted by sefacanacar on 07/03/2008 10:11am

    i wrote and debug the code with no error but when i pushed the play button it did not played the .wav file. can anyone help me?

    Reply
  • Won't work unless!

    Posted by Legacy on 01/20/2004 12:00am

    Originally posted by: Patrick

    Don't forget to add:

    using System.Runtime.InteropServices;

    otherwise it won't work!!!

    Kind regards,

    Patrick

    Reply
  • thanks

    Posted by Legacy on 12/02/2003 12:00am

    Originally posted by: ajis

    Thank you for all programming in c#

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

Top White Papers and Webcasts

  • IT decision support impacts all aspects of technology management, from governance and strategy to budgets and resource planning. IT decision support effectiveness often falls prey to data-driven challenges that make it difficult to understand the data in context. These challenges: overwhelming data volumes, heterogeneous data types, and growing data complexity. This Forrester Consulting Paper reports the three key findings from their study conducted, on behalf of BDNA, to test the hypothesis that data …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds