HomeSearch

C# SoundPlayer: Play WAV Files

Use the SoundPlayer type to play a WAV file. Use a using-block for SoundPlayer.
SoundPlayer. The SoundPlayer type 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. You can call PlaySync to play it.
Example. The System.Media namespace in the .NET Framework does not contain many types. One type it contains is SoundPlayer. This type is useful for many different functions. It requires a WAV file.

Here: In this example, we use the using-statement syntax to ensure correct resource acquisition. We specify an arbitrary sound file.

Using

Note: You must have a WAV file at the specified location on your disk for the code to work.

C# program that uses SoundPlayer 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(); } } }
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.

Tip: If you want the program to continue to some other operation after the sound starts, use the Play method instead.

Discussion. 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. The PlayLooping method can be used to loop a sound.
Summary. 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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls