Codelog

foreach(Snippet aSnippet in CodeLog){ aSnippet.GetSolution(); }

Archive for the ‘Media’ tag

Playing sounds in C#

with 4 comments

Its fairly easy to play sounds in C#. .NET 2.0 comes with two main classes to assist you with this. SystemSounds, SoundPlayer and SystemSound (which is a abstract base class). The SystemSounds class is very simple to use. It has the predefined system sounds in it. For example, if you wanna play an asterisk sound on the click of a button, then simple add the statement,

System.Media.SystemSounds.Asterisk.Play();  //This will spawn a new thread that will play the sound

This class has Asterisk, Beep, Exclamation, Hand and Question in it. How ever if you wanna play some other wav files, then you need to use the SoundPlayer class. To use this, you need to create an object of this class and provide the path of the sound file as string or the sound itself as stream, then load the file and play it. Isn’t it simple ??

Here is a sample,

System.Media.SoundPlayer aSoundPlayer = new System.Media.SoundPlayer(@"C:\Documents and Settings\codelog\My Documents\LASER.WAV");  //Creates a sound player with the mentioned file. You can even load a stream in to this class


aSoundPlayer.Play();  //Plays the sound in a new thread

This is how I play sounds in C#. If you know some other way comment on it.

Written by sudarsanyes

December 18th, 2008 at 10:45 am