在变量中存储.WAV文件

时间:2014-07-11 20:59:52

标签: vb.net variables object wav audio

我有3个.wav文件,我希望我的用户可以选择。

然后我进入了一个ComboBox,并选择了这样。

Public ChosenSound As Object

-

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        If ComboBox1.SelectedItem = "Beep" Then
            ComboBox1.Text = "Beep"
            ChosenSound = My.Resources.beeps
            PlayBackgroundSoundResource()
        End If
        If ComboBox1.SelectedItem = "Chime" Then
            ComboBox1.Text = "Chime"
            ChosenSound = My.Resources.chime
            PlayBackgroundSoundResource()
        End If
        If ComboBox1.SelectedItem = "Chirp" Then
            ComboBox1.Text = "Chirp"
            ChosenSound = My.Resources.chirp
            PlayBackgroundSoundResource()
        End If
End Sub

-

Sub PlayBackgroundSoundResource()
    Try
        My.Computer.Audio.Play(ChosenSound, AudioPlayMode.Background)
    Catch ex1 As Exception
        MessageBox.Show(ex1.Message)
        Return
    End Try
End Sub

通过ComboBox选择时,每个声音都能完美播放,但一旦通过其他方式播放声音,I。按下按钮,我收到以下错误:

---------------------------

---------------------------
The wave header is corrupt.
---------------------------
OK   
---------------------------

以下是按下按钮的代码:

Private Sub optionsBTNtestsound_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optionsBTNtestsound.Click
    PlayBackgroundSoundResource()
End Sub

我这样做是错的吗?为什么我的声音只能在ComboBox选择后播放,而不是以任何其他方式调用?

1 个答案:

答案 0 :(得分:2)

正如我在上面的评论中所说,流可能不在开头,因此这就是为什么你看到The wave header is corrupt为了解决这个问题,不要依赖Audio.Play作为流可能仍然没有完成和你的错误的原因。这需要一个流和播放模式,如果您选择项目左右,流未完成,然后您尝试播放另一个文件时,流不在最后。

这是尝试过的&测试

Private LastFile As String = String.Empty 'Holds the last selected item

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    PlayBackgroundSoundResource(ComboBox1.SelectedItem.ToString) 'Call your method
    LastFile = ComboBox1.SelectedItem.ToString.Trim 'Set your variable to the last item
End Sub

Private Sub PlayBackgroundSoundResource(ByVal strItem As String)
    Dim sPlayer As New System.Media.SoundPlayer 'Create new instance of the soundplayer

    Select Case strItem.Trim
        Case "Beep"
            sPlayer.Stream = My.Resources.beeps
        Case "Chime"
            sPlayer.Stream = My.Resources.chime
        Case "Chirp"
            sPlayer.Stream = My.Resources.chirp
    End Select

    sPlayer.Play() 'Play the file

    If sPlayer IsNot Nothing Then sPlayer = Nothing
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    PlayBackgroundSoundResource(LastFile) 'Play the last file that was selected
End Sub