0

我想要做的是在指定的时间内播放音乐文件,然后停止播放。但是,正在播放整个音乐文件。我不能使用“PlaySync()”方法,因为我不能阻止线程。

4

2 回答 2

2

也许是这样的

 Task.Factory.StartNew(() =>
   {
    var player = new SoundPlayer();
    player.SoundLocation = "myfile";
    player.Play();
    Thread.Sleep(duration)
    player.Stop();
   });
于 2011-12-16T09:41:32.577 回答
2

您不必自己生成一个新线程,因为SoundPlayer.Play方法本身就是这样做的。

试试这个版本:

public void Play() 
    { 
        player = new SoundPlayer(); 
        player.SoundLocation = "myfile"; 
        Timer timer = new Timer(); 
        timer.Tick += (s,e) => 
            {
                player.Stop();
                timer.Stop();
            };
        timer.Interval = duration; 
        player.Play();
        timer.Start(); 
    } 
于 2011-12-16T09:49:53.367 回答