10.10. Play a WAV File

Problem

You need to play a WAV file.

Solution

Create a new instance of the System.Media.SoundPlayer class, pass the location or stream of the WAV file, and invoke the Play method.

How It Works

The System.Media namespace, first introduced in .NET Framework 2.0, contains a SoundPlayer class. SoundPlayer contains constructors that let you specify the location of a WAV file or its stream. Once you have created an instance, you just need to invoke the Play method to play the file. The Play method creates a new thread to play the sound and is thus asynchronous (unless a stream is used). For playing the sound synchronously, use the PlaySync method. Note that SoundPlayer supports only the WAV format.

Before a file is played, it ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.