You want to play a sound clip file, a system sound, or a music file such as an MP3.
Several different objects and system utilities are available to play sound clips or media files. In this recipe we'll demonstrate the use of:
The code required to play an audio sample is actually quite short. In most cases, a single line of code is all it takes to play a sound. Visual Basic 2005's new My namespace provides a lot of new easy-to-use functionality. The My.Computer.Audio.Play() method is a good example. Simply pass this method the name of an audio file and the play mode that controls how the sound is played:
My.Computer.Audio.Play("sample.wav", _ AudioPlayMode.WaitToComplete)
The AudioPlayMode.WaitToComplete option causes the program to wait for the sound to complete before proceeding. The two other members of this enumeration are Background (plays a sound once in the background) and BackgroundLoop (loops the sound repeatedly in the background). To stop a background looping sound, issue this command:
Another way to play sounds is with a SoundPlayer class instance. This works a lot like the My.Computer.Audio features because those features depend on the SoundPlayer class:
Dim player As New SoundPlayer("sample.wav") player. Play( )
The SoundPlayer object provides quite a few properties and methods to control the playing of sound files, and you should check these out if you need special functionality in your application. For example, the Stop() and Play() methods allow you to pause and restart the sound in the middle of the content.
Windows includes several user-configured sounds for various system-level events. For example, when validating user-entered data, you can play the system-assigned sound for Exclamation in coordination with a custom visual message to inform the user of some issue with the input data:
Some sound formats are beyond the basic capabilities of the My.Computer.Audio features. To play these sounds, you can defer to the default applications designated to play sound files with specific extensions. The following lines of code start whatever program is currently assigned to play MP3 files, passing it the name of the MP3 file to be played. Often this will start the Windows Media Player, but the user may have some other program configured to play such files. The Process.Start() method tells the operating system to play the file using its current settings:
Dim soundProgram As Process = Process.Start("sample.mp3") soundProgram.WaitForExit( )