2011-03-09 95 views
1

我正在VB.NET中編寫一個簡單的小程序,它必須同時播放兩個聲音。爲什麼Media.SoundPlayer.Play()實際上在兩次調用時啓動兩個新線程?

問題是,當我立即調用SoundPlayer.Play()兩次時,後面的調用看起來像是「接管」由第一次調用創建的線程,而不是創建一個新線程,就像它說的它應該做in the docs

任何想法我做錯了什麼?

我用下面的代碼:

Private Sub Button_OFD_Sound1_Browse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_OFD_Sound1_Browse.Click 
    LoadSound(OFD_Sound1, TextBox_OFD_Sound1_SelectedFile, SoundPlayer_Sound1) 
End Sub 

Private Sub Button_OFD_Sound2_Browse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_OFD_Sound2_Browse.Click 
    LoadSound(OFD_Sound2, TextBox_OFD_Sound2_SelectedFile, SoundPlayer_Sound2) 
End Sub 

Private Sub Button_PlaySounds_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_PlaySounds.Click 
    If SoundPlayer_Sound1.IsLoadCompleted And SoundPlayer_Sound2.IsLoadCompleted Then 
     SoundPlayer_Sound1.Play() 
     SoundPlayer_Sound2.Play() 
    Else 
     MsgBox("Der er ikke indlæst nogen lydfil.", MsgBoxStyle.Exclamation, "Der opstod en fejl") 
    End If 
End Sub 

Private Sub LoadSound(ByVal FileSelectorDialog As Windows.Forms.OpenFileDialog, ByVal SelectedFileTextBox As Windows.Forms.TextBox, ByVal SoundPlayer As Media.SoundPlayer) 
    If FileSelectorDialog.ShowDialog() = Windows.Forms.DialogResult.Cancel Then Return 
    If IO.File.Exists(FileSelectorDialog.FileName) Then 
     SoundPlayer.SoundLocation = FileSelectorDialog.FileName 
     SoundPlayer.Load() 
     If SoundPlayer.IsLoadCompleted Then 
      SelectedFileTextBox.Text = FileSelectorDialog.FileName 
     Else 
      MsgBox("Den valgte lydfil kunne ikke indlæses. Det skyldes muligvis, at filen ikke er i det understøttede WAVE-format. Prøv at vælge en anden.", MsgBoxStyle.Exclamation, "Der opstod en fejl") 
     End If 
    Else 
     MsgBox("Den valgte fil eksisterer ikke. Vælg en anden fil.", MsgBoxStyle.Exclamation, "Der opstod en fejl") 
    End If 
End Sub 

回答

3

它說的是會在後臺線程玩文檔,而不是每個聲音將使用單獨線播放。這是因爲它不會在播放聲音時凍結GUI,所以它確保它不會在GUI線程中播放。但是,它只支持一次播放一個聲音。它只支持wav,沒有音量變化,沒有暫停。所以它只支持非常基本的功能,比如播放短暫的聲音以發出警告等。

如果您需要比此功能更多的功能(並且您通常會這樣做),請查看MediaPlayer類。

+0

當您製作Windows Forms應用程序時,似乎沒有MediaPlayer類可用:/ – 2011-03-09 12:35:39

+0

嘗試添加對PresentationCore.dll的引用。你可以在System.Windows.Media命名空間中找到它。 – 2011-03-09 13:05:39

+0

它的工作!謝謝! :d – 2011-03-09 15:03:44

相關問題