2016-05-21 148 views
0

如何檢查我已播放的聲音是否完成? 我使用C#.NET WinForms和我的播放聲音的代碼是:檢查聲音是否完成c#

SoundPlayer s = new SoundPlayer(@"c:\intro.wav"); 
     s.Play(); 

的人誰需要知道的進口,這是using System.Media;

所以,我需要知道什麼時候我的聲音完成玩,然後我需要運行一些代碼。我知道我可以使用計時器,但我想避免這樣做,因爲特定的原因。 預先感謝您。

回答

0

默認情況下,SoundPlayer在單獨的線程上運行,但有一種方法可在當前線程上播放聲音。見PlaySync

private SoundPlayer Player = new SoundPlayer(); 
private void loadSoundAsync() 
{ 
    // Note: You may need to change the location specified based on 
    // the location of the sound to be played. 
    this.Player.SoundLocation = "http://www.tailspintoys.com/sounds/stop.wav"; 
    this.Player.LoadAsync(); 
} 

private void Player_LoadCompleted (
      object sender, 
      System.ComponentModel.AsyncCompletedEventArgs e) 
{ 
    if (this.Player.IsLoadCompleted) 
    { 
     this.Player.PlaySync(); 
    } 
} 
2

您可以創建一個任務,等待無阻塞你的UI線程...

async void Test() 
{ 
    using (var player = new System.Media.SoundPlayer(@"C:\Windows\Media\Alarm01.wav")) 
    { 
     await Task.Run(() => { player.Load(); player.PlaySync(); }); 
     MessageBox.Show("Finished. Now you can run your code here"); 
    } 
}