Section 3.4. Play Sounds


3.4. Play Sounds

.NET 2.0 provides a new SystemSounds class that allows you to play the most common Windows system sounds with a single line of code, no matter where they are located on your operating system. In addition, the SoundPlayer control will play .wav files with nearly no coding.

3.4.1. How do I do that?

Create a new Windows application project, name it Sounds, and drag a button (button1) onto the form. Set the text of the button to System Sound (you'll have to stretch the button to make room for the words).


Tip: Setting text in the button is not required, but it does make it easier to play with this test application.

Double-click the button and you'll go to its Click event handler. In the code stub for the event handler, type the keyword SystemSounds followed by a period (.). The list of system sounds you can play is displayed, as shown in Figure 3-18.

Figure 3-18. System sounds


Choose Asterisk, type a period (.), and then choose Play from the list presented by IntelliSense. The result is the following code:

SystemSounds.Asterisk.Play( );

Run the application, and then press the button (labeled System Sound). Voila! A system sound!

To play a .wav file, add a SoundPlayer control to the form. It is immediately dropped into the tool panel at the bottom of the form.

You can tell this SoundPlayer control to play a .wav file by setting its SoundLocation property, or you can ask it to play a sound from a stream-based object (perhaps obtained over the Web) by setting its Stream property.

Add a second button (button2) to the form and set its text to "WAV File." Double-click the button, and in the event handler, add code to hardwire your SoundPlayer control to a .wav file on your computer, as shown in the following fragment:

private void button2_Click(object sender, EventArgs e) {    this.soundPlayer1.SoundLocation = @"C:\Windows\Media\Chimes.wav";    this.soundPlayer1.Play( ); }

3.4.2. What about...

...playing the audio synchronously and waiting for it to complete before returning control to the application?

Sure, you can do this. Instead of calling the Play method, call the PlaySync method. This will play your .wav file in the same thread as the application. You can also call PlayLooping, which works just like Play except that it keeps playing until you tell it to stop by calling, logically enough, Stop.

3.4.3. Where can I learn more?

For more information on the sound player and on playing sounds, see the MSDN Documentation article "Sound Player Class Overview."



Visual C# 2005(c) A Developer's Notebook
Visual C# 2005: A Developers Notebook
ISBN: 059600799X
EAN: 2147483647
Year: 2006
Pages: 95
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net