2011-12-16 86 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(); 
            });