Title: Play WAV files in C#
The System.Media.SoundPlayer class lets you easily play WAV files. This example uses the following PlayWav method to play WAV files.
// The player making the current sound.
private SoundPlayer Player = null;
// Dispose of the current player and
// play the indicated WAV file.
private void PlayWav(string filename, bool play_looping)
{
// Stop the player if it is running.
if (Player != null)
{
Player.Stop();
Player.Dispose();
Player = null;
}
// If we have no file name, we're done.
if (filename == null) return;
if (filename.Length == 0) return;
// Make the new player for the WAV file.
Player = new SoundPlayer(filename);
// Play.
if (play_looping)
Player.PlayLooping();
else
Player.Play();
}
This method first determines whether a SoundPlayer is running and stops it if it is.
Next if the filename parameter is missing or blank, the method exits. That lets the program stop the current sound without starting a new one.
The method then creates a new SoundPlayer for the desired WAV file and then starts it, either with the player's Play or PlayLooping method.
The following code shows how the example plays the file Chicks.wav when you check the chicks radio button.
private void radChicks_Click(object sender, EventArgs e)
{
PlayWav("Chicks.wav", true);
}
Note that the SoundPlayer class cannot play multiple WAV files at the same time, even if you use multiple SoundPlayer objects. That means if you use the SoundPlayer to play a WAV file, the player automatically stops any WAV files that it is currently playing.
Download the example to experiment with it and to see additional details.
|