为什么Media.SoundPlayer.Play()实际上在两次调用时启动两个新线程?

问题描述:

我正在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 

它说的是会在后台线程玩文档,而不是每个声音将使用单独线播放。这是因为它不会在播放声音时冻结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