2013-12-12 38 views
2

我使用此代碼播放聲音並在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 

我想聲音循環,直到用戶窗體上的按鈕被按下來停止它,但我不知道如何實現這一點。如果你能指出我正確的方向(就如何編碼這一點),將非常感激。非常感謝

+0

你是說聲音應該在循環中播放和其它活動可以並行發生的呢? –

+0

@PankajJaju當用戶窗體被激活時,我不需要任何其他事件發生,當聲音循環時,所有內容都可以暫停,然後當按下按鈕時,所有事情都會恢復正常。 – user3049027

回答

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 
+0

這將播放與循環播放一樣快的聲音,試試看看會發生什麼...... – bendataclear

+0

我試過了,它不工作。它在'Loop Until StopSound'行的'StopSound'上給我一個變量未定義的錯誤。 – user3049027

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

+0

這是正確的,是的,我正在使用該API。我現在切換到你的代碼,它的工作很好 - 謝謝! – user3049027

+0

很高興能有所幫助:) –

+0

@SiddharthRout幫我也! –