Use the SoundPlayer class to play a WAV file in C#

The System.Media.SoundPlayer class lets you easily play .WAV files. This example uses the following code to play the file Croak.wav when you click the frog button.

// Play the frog sound.
private void btnFrog_Click(object sender, EventArgs e)
{
    using (SoundPlayer player = new SoundPlayer("Croak.wav"))
    {
        player.Play();
    }
}

The creates a SoundPlayer, passing the constructor the location of the WAV file to play. In this example the file is in the executable directory. If it were in some other directory, you could pass in the file's complete path.

After creating the SoundPlayer, the code calls the new object's Play method to play the file synchronously.

The following code shows how the example plays the file Chicks.wav when you check the Chicks CheckBox.

// Turn the chicks on or off.
SoundPlayer ChicksPlayer = new SoundPlayer("Chicks.wav");
private void chkChicks_CheckedChanged(object sender, EventArgs e)
{
    if (chkChicks.Checked)
    {
        ChicksPlayer.PlayLooping();
    }
    else
    {
        ChicksPlayer.Stop();
    }
}

When the form loads, the program creates the SoundPlayer, passing its constructor the name of the file to play. When the CheckBox is checked or unchecked, the code starts or stops the player. This code calls the player's PlayLooping method to make it play the sound resource repeatedly on a separate thread while the program continues executing.

Note that SoundPlayer objects can only play one WAV file at a time even if you use multiple objects. That means, for example, that playing any WAV file with a SoundPlayer automatically stops any file that is currently playing. (In this example, the CheckBoxes are only correct if you use them to stop their sounds. For example, if you start the bees buzzing and then click the frog button, the bees will stop even though their CheckBox is still checked.)

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.