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

The System.Media.SoundPlayer class lets you easily play .WAV files. For this example, first add the WAV file as a resource. To do that, open the Project menu and select Properties. Then open the Add Resource dropdown and select Add Existing File. Select the WAV file and click Open.

Now the program can use a SoundPlayer object and the resource to play the file. The following code shows how this example plays the Croak WAV resource when you click the frog button.

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

The creates a SoundPlayer, passing the constructor the WAV resource to play. It then calls the new object's Play method to play the file synchronously.

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

// Turn the chicks on or off.
SoundPlayer ChicksPlayer = new SoundPlayer(Properties.Resources.Chicks);
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. 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.