Play Simple WAV Audio

Neither .NET 1.0 or .NET 1.1 provided a managed way to play audio. This shortcoming is finally addressed in .NET 2.0 with the new SoundPlayer class, which allows you to play audio synchronously or asynchronously.

Note

Using the SoundPlayer class, you can play WAV files without diving into the Windows API.

How do I do that?

You can instantiate a SoundPlayer object programmatically, or you can add one to the component tray by dragging it from the toolbox at design time. Once you've created the SoundPlayer, you need to point it to the sound content you want to play. You do this by setting one of two properties:

SoundLocation

If you have a file path or URL that points to a WAV file, specify this information in the SoundLocation property.

Stream

If you have a Stream-based object that contains WAV audio content, use the Stream property.

Once you've set the Stream or SoundLocation property, you need to tell SoundPlayer to actually load the audio data by calling the Load( ) or LoadAsync( ) method. The Load( ) method pauses your code until all the audio is loaded into memory. On the other hand, LoadAsync( ) carries out its work on another thread and fires the LoadCompleted event once it's finished and the audio's available. Usually, you'll use Load() unless you have an extremely large audio file or it takes a long time to read the whole audio file (for example, when retrieving the audio over a slow network or Internet connection).

Finally, once the audio is available, you ...

Get Visual Basic 2005: A Developer's Notebook 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.