TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Play Sounds With SoundPlayer: WAV

This C# example program uses the SoundPlayer type to play a WAV file.

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();
	}
    }
}

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf