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:
SoundLocationIf you have a file path or URL that points to a WAV file, specify this information in the
SoundLocationproperty.StreamIf you have a
Stream-based object that contains WAV audio content, use theStreamproperty.
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access