Udostępnij za pośrednictwem


How to: Play Sounds and Wait For Completion in Visual Basic

This example plays sounds from a sound file and an application resource using the My.Computer.Audio.Play method, and waits for them to complete.

Background playing lets the application execute other code while the sound plays. The My.Computer.Audio.Play method allows the application to play only one background sound at a time; when the application plays a new background sound, it stops playing the previous background sound.

The My.Computer.Audio class provides methods and properties that can be used to play audio files.

Example

The My.Computer.Audio.Play method plays the specified sound and waits for it to complete.

Check that the file name references a .wav sound file on your system.

Sub PlaySoundFile()
    My.Computer.Audio.Play("C:\Waterfall.wav", _
        AudioPlayMode.WaitToComplete)
End Sub

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms Applications > Sound. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).

The My.Computer.Audio.Play method plays the specified sound and waits for it to complete.

Check that the application resources include a .wav sound file named Waterfall.

Sub PlaySoundResource()
    My.Computer.Audio.Play(My.Resources.Waterfall, _
        AudioPlayMode.WaitToComplete)
End Sub

Compiling the Code

These code examples can run only within a Windows Forms or console application. For more information, see My.Computer.Audio.Play Method.

Robust Programming

The file name should reference a .wav sound file on your system.

To simplify the management of your sound files, consider storing the files as application resources. They can then be accessed through the My.Resources Object.

See Also

Tasks

How to: Play System Sounds in Visual Basic

How to: Play Sounds in Visual Basic

Reference

My.Computer.Audio.Play Method

AudioPlayMode Enumeration

My.Computer.Audio Object