如何循环播放声音

时间:2013-12-12 11:06:43

标签: excel excel-vba vba

我正在使用此代码播放声音,并在excel中按下命令按钮时打开用户窗体。

Private Sub CommandButton4_Click()
    Call PlayIt
    RequestAssistanceUserForm.Show
End Sub

Sub PlayTheSound(ByVal WhatSound As String)
    If Dir(WhatSound, vbNormal) = "" Then
        ' WhatSound is not a file. Get the file named by
        ' WhatSound from the Windows\Media directory.
        WhatSound = Environ("SystemRoot") & "\Media\" & WhatSound
        If InStr(1, WhatSound, ".") = 0 Then
            ' if WhatSound does not have a .wav extension,
            ' add one.
            WhatSound = WhatSound & ".wav"
        End If
        If Dir(WhatSound, vbNormal) = vbNullString Then
            Beep            ' Can't find the file. Do a simple Beep.
            Exit Sub

        End If
    Else
        ' WhatSound is a file. Use it.
    End If
    sndPlaySound32 WhatSound, 0&    ' Finally, play the sound.
End Sub

Sub PlayIt()
    PlayTheSound "tada.wav"
End Sub

我希望声音循环直到按下用户窗体上的按钮才能停止它,但我不知道如何实现这一点。如果你能够指出我正确的方向(就如何编码而言),我将非常感激。非常感谢

2 个答案:

答案 0 :(得分:3)

你需要使用const Const SND_LOOP = &H8,它将继续循环播放声音,直到下一次调用PlaySound为止。

我相信您使用的API是

Public Declare Function sndPlaySound32 _
Lib "winmm.dll"  Alias "sndPlaySoundA" (ByVal lpszSoundName As String, _
ByVal uFlags As Long) As Long

使用我在下面使用的那个。

试试这个

Declare Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" _
(ByVal lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) As Long

Const SND_LOOP = &H8
Const SND_ASYNC = &H1

Sub StartSound()
    PlaySound "C:\Windows\Media\Chimes.wav", ByVal 0&, SND_ASYNC + SND_LOOP
End Sub

Sub StopSound()
    PlaySound vbNullString, ByVal 0&, SND_ASYNC
End Sub

有关API HERE- My Fav stop for API's

的更多信息

答案 1 :(得分:0)

您可以简单地循环PlayTheSound来电,也可以调用DoEvents以允许Excel处理点击停止按钮

' At Module scope
Private StopSound As Boolean

Sub PlayIt()
    Do
        PlayTheSound "tada.wav"
        DoEvents
    Loop Until StopSound
    StopSound = False
End Sub

Private Sub StopCommandButton_Click()
    StopSound = True
End Sub
相关问题