2011-12-16 31 views
2

我想要做的是播放音乐文件达指定的时间,然后停止播放。但是,整个音乐文件正在播放。有任何想法吗?如何在指定的时间内播放音乐文件

我试过开始一个新的线程,仍然没有工作。

+0

是否使用普通的C#这一点,或者你正在使用XNA框架吗? – 2011-12-16 10:13:04

回答

0

问题是PlaySync会阻塞该线程,所以其他消息将不会被处理。这包括来自Tick事件的停止命令。你必须使用普通的Play函数,它将是异步的,并创建一个新线程来播放文件。根据应用程序的工作方式,你将不得不处理最终的多线程情况。

+0

我试过这样做,并更新了上面的代码。请你看看,因为它还没有工作?我猜这是一个线程问题。 – 2011-12-16 09:13:49

+0

你的程序的其余部分是做什么的?你的代码大部分工作,除了你应该Stop()和Dispose()在ClockTick上的定时器来停止计时器反复发射。如果您的程序在最后退出,则该文件将无法播放,就像您有一个不等待任何用户输入的控制台应用程序一样。 – 2011-12-20 09:57:28

0

我会建立一些类似于这样的东西:它只是在编辑窗口中手写而已,所以不要指望它像这样编译。这只是为了说明这个想法。

internal class MusicPlayer 
{ 
    private const int duration = 1000; 
    private Queue<string> queue; 
    private SoundPlayer soundPlayer; 
    private Timer timer; 

    public MusicPlayer(params object[] filenames) 
    { 
     this.queue = new Queue<string>(); 
     foreach (var filenameObject in filenames) 
     { 
      var filename = filenameObject.ToString(); 
      if (File.Exists(filename)) 
      { 
       this.queue.Enqueue(filename); 
      } 
     } 

     this.soundPlayer = new SoundPlayer(); 
     this.timer = new Timer(); 
     timer.Elapsed += new System.Timers.ElapsedEventHandler(ClockTick); 
    } 

    public event EventHandler OnDonePlaying; 

    public void PlayAll() 
    { 
     this.PlayNext(); 
    } 

    private void PlayNext() 
    { 
     this.timer.Stop(); 
     var filename = this.queue.Dequeue(); 
     this.soundPlayer.SoundLocation = filename; 
     this.soundPlayer.Play(); 
     this.timer.Interval = duration; 
     this.timer.Start(); 
    } 

    private void ClockTick(object sender, EventArgs e) 
    { 
     if (queue.Count == 0) { 
      this.soundPlayer.Stop(); 
      this.timer.Stop(); 
      if (this.OnDonePlaying != null) 
      { 
       this.OnDonePlaying.Invoke(this, new EventArgs()); 
      } 
     } 
     else 
     { 
      this.PlayNext(); 
     } 
    } 
} 
0

试试这个:

ThreadPool.QueueUserWorkItem(o => { 
            note.Play(); 
            Thread.Sleep(1000); 
            note.Stop(); 
            });