播放声音 (Visual Basic)

My.Computer.Audio 对象提供播放声音的方法。

播放声音

后台播放允许应用程序在声音播放时执行其他代码。 该方法 My.Computer.Audio.Play 允许应用程序一次只播放一个背景声音;当应用程序播放新的背景声音时,它将停止播放以前的背景声音。 你也可以播放一种声音并等待其播放完毕。

在以下示例中,My.Computer.Audio.Play 方法会播放一个声音。 当指定AudioPlayMode.WaitToComplete时,My.Computer.Audio.Play会等待声音完成,然后再继续调用代码。 使用此示例时,应确保文件名引用计算机上.wav声音文件

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

在以下示例中,My.Computer.Audio.Play 方法会播放一个声音。 使用此示例时,应确保应用程序资源包含名为 Waterfall 的.wav声音文件。

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

播放循环声音

在以下示例中,当指定My.Computer.Audio.Play时,PlayMode.BackgroundLoop方法会在后台播放指定的声音。 使用此示例时,应确保文件名引用计算机上的.wav声音文件。

Sub PlayLoopingBackgroundSoundFile()
    My.Computer.Audio.Play("C:\Waterfall.wav",
        AudioPlayMode.BackgroundLoop)
End Sub

在以下示例中,当指定My.Computer.Audio.Play时,PlayMode.BackgroundLoop方法会在后台播放指定的声音。 使用此示例时,应确保应用程序资源包含名为 Waterfall 的.wav声音文件。

Sub PlayLoopingBackgroundSoundResource()
    My.Computer.Audio.Play(My.Resources.Waterfall,
          AudioPlayMode.BackgroundLoop)
End Sub

前面的代码示例也可用作 IntelliSense 代码片段。 在代码片段选取器中,它位于 Windows 窗体应用程序 > 声音中。 有关详细信息,请参阅 代码片段

通常,当应用程序播放循环声音时,它最终应停止声音。

停止播放背景声音

My.Computer.Audio.Stop使用该方法停止应用程序当前播放的背景或循环声音。

通常,当应用程序播放循环声音时,它应在某个时间点停止声音。

下面的示例将停止播放背景声音。

Sub StopBackgroundSound()
    My.Computer.Audio.Stop()
End Sub

前面的代码示例也可用作 IntelliSense 代码片段。 在代码片段选取器中,它位于 Windows 窗体应用程序 > 声音中。 有关详细信息,请参阅 代码片段

播放系统声音

使用My.Computer.Audio.PlaySystemSound方法播放指定的系统声音。

该方法 My.Computer.Audio.PlaySystemSound 采用类中的共享成员 SystemSound 之一作为参数。 系统声音 Asterisk 通常表示错误。

以下示例使用My.Computer.Audio.PlaySystemSound方法播放系统声音。

Sub PlaySystemSound()
    My.Computer.Audio.PlaySystemSound(
        System.Media.SystemSounds.Asterisk)
End Sub

另请参阅