C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
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(); } } } 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.
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.