检查声音何时完成c#

时间:2016-05-21 19:20:20

标签: c# audio

如何检查我播放的声音是否已完成? 我正在使用C#.Net Winforms,我播放声音的代码是:

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

对于需要了解导入的任何人,都是using System.Media;

所以我需要知道我的Sound何时播放完毕,然后我需要运行一些代码。我知道我可能会使用计时器,但我想不要因为特定原因而这样做。 提前谢谢。

2 个答案:

答案 0 :(得分: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");
    }
}

答案 1 :(得分: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();
    }
}