
SoundPlayer plays sounds or music. It works directly in your C# program. With the System.Media namespace, you can use this type to load any WAV file and play it.
First, the System.Media namespace in the .NET Framework does not contain many types, but the SoundPlayer type is very useful for many different functions. It requires a WAV file. In this example, we use the using-statement syntax to ensure correct resource acquisition semantics. We specify an arbitrary sound file as the WAV file; you must have a WAV file at the specified location for the code to work.
This C# example program uses the SoundPlayer type to play a WAV file.
Program that uses SoundPlayer [C#]
using System.Media;
class Program
{
static void Main()
{
// Create new SoundPlayer in the using statement.
using (SoundPlayer player = new SoundPlayer("C:\\bass.wav"))
{
// Use PlaySync to load and then play the sound.
// ... The program will pause until the sound is complete.
player.PlaySync();
}
}
}
Result
(The target WAV is loaded and played through the speakers.)
Why use PlaySync? If you just call the Play method in this program, the program will terminate before the sound plays. The Sync indicates that the program should pause while the sound plays. If you want the program to continue to some other operation after the sound starts, use the Play method instead.
The SoundPlayer type provides more functionality than is shown here. It presents a simple set of event handlers, and also can do asynchronous operations if you need them. Finally, the PlayLooping method can be used to loop a sound endlessly in a new thread.

The SoundPlayer is an interesting type found in the System.Media namespace in the .NET Framework. You can play WAV sounds synchronously or asynchronously using the Play methods. It does not support a wide variety of file formats.
Console Programs