2013-07-02 48 views
1

我一直在研究一個程序,該程序具有允許用戶選擇播放程序的WAV聲音的功能。VB.NET(2008)播放聲音

由於此功能被放置在選擇對話,我希望這樣的事情發生:

1)點擊按鈕

2)該按鈕可以從改變圖像爲B和聲音播放

a)用戶不喜歡的聲音,並希望停止 - 再點擊並進入3)

3)聲音到達終點和圖像回來A.

我的主要目標是允許用戶隨時中斷聲音(在步驟2a)。

我已經試過兩種方法:

Dim p as New Media.SoundPlayer 

p.SoundLocation = fn 'Where fn is the FileName, the WAV location 
p.Play 

這個工程出精品,除了當聲音達到其最終我無法檢測,甚至當我試圖用p.Stream.Length和P。 Stream.Position會返回一個錯誤,因爲它實際上是空的,當它不是時(我試圖用Stream表示的WAV嘗試My.Computer.Audio.Play),這些屬性甚至在聲音停止之前具有相同的值。

在此之後,我想:

My.Computer.Audio.Play(fn,AudioPlayMode.WaitToComplete) 

但會發生什麼,因爲我懷疑,是該程序沒有響應,直到聲音結束,禁止用戶中斷,或做任何事情。

幸運的是,System.Media.SoundPlayer允許您使用事件聲明,就像這樣:

Private WithEvents p as System.Media.SoundPlayer 

即使,沒有這些事件都做什麼,我需要的是有用的。

有什麼建議嗎? 在此先感謝

+0

我現在開始懷疑我將不得不使用AudioPlayMode.BackgroundLoop 所以程序等待用戶來阻止它,即使我不希望做的程序循環的聲音...... – K09P

回答

0

下面是使用mciSendString()API,它可以讓你PLAY取消 WAV文件的解決方案,同時也給你的WAV文件已完成播放通知:

Imports System.Runtime.InteropServices 
Public Class Form1 

    Private PlayingWav As Boolean = False 
    Private Const MM_MCINOTIFY As Integer = 953 

    <DllImport("winmm.dll")> _ 
    Private Shared Function mciSendString(_ 
     ByVal command As String, _ 
     ByVal buffer As System.Text.StringBuilder, _ 
     ByVal bufferSize As Integer, _ 
     ByVal hwndCallback As IntPtr _ 
     ) As Integer 
    End Function 

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 
     If Not PlayingWav Then 
      PlayWavFile(TextBox1.Text) 
     Else 
      StopWavFile() 
     End If 
    End Sub 

    Public Sub PlayWavFile(ByVal WavFilePath As String) 
     Dim cmd As String = "open " & Chr(34) & WavFilePath & Chr(34) & " type waveaudio alias wav" 
     If mciSendString(cmd, Nothing, 0, IntPtr.Zero) = 0 Then 
      PlayingWav = True 
      Button1.Text = "Stop" 
      mciSendString("play wav notify", Nothing, 0, Me.Handle) 
     Else 
      MessageBox.Show(WavFilePath, "Error Loading Wav", MessageBoxButtons.OK, MessageBoxIcon.Error) 
     End If 
    End Sub 

    Public Sub StopWavFile() 
     mciSendString("close wav", Nothing, 0, IntPtr.Zero) 
    End Sub 

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) 
     Select Case m.Msg 
      Case MM_MCINOTIFY 
       WavStopped() 

     End Select 
     MyBase.WndProc(m) 
    End Sub 

    Private Sub WavStopped() 
     PlayingWav = False 
     Button1.Text = "Play" 
    End Sub 

End Class 
+0

對不起,我最近一直很忙......它不能工作得更好!非常感謝 :) – K09P