3.8. Play Simple WAV AudioNeither .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. 3.8.1. 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:
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 can call one of the following methods:
To halt asynchronous playback at any time, just call Stop( ). The following code snippet shows an example that plays a sample sound synchronously: Dim Player As New SoundPlayer( ) Player.SoundLocation = Application.StartupPath & "\mysound.wav" Try Player.Load( ) Player.PlaySync( ) Catch Err As Exception ' An error will occur here if the file can't be read ' or if it has the wrong format. End Try 3.8.2. What about......other types of audio? Unfortunately, the SoundPlayer can only play the WAV audio format. If you want to play other types of multimedia, like MP3 or WMA files, you need to use a different solution, and there are no managed classes to help you out. Two options include:
|