2012-07-14 53 views
0

我目前正在使用c#和winforms播放mp3文件这个tutorial,但我添加了一个datagridview列出的歌曲,现在当我点击一个歌曲在网格中播放的歌曲很好,但它只播放一首歌曲,我想要做的就是一旦歌曲完成播放,移动到列表中的下一首歌曲。我已经尝试过使用Audiolenght的Thread.Sleep作为时间,但它只是停止整个应用程序的工作,直到完成了睡眠,而这完全不是我想要的,对于winforms我有点新奇,所以如果任何人都可以指导我到我需要改变以使其工作,我真的很感激它。这里是我的代码,我已经这么远:Mp3播放类播放歌曲的列表,但等到一个完成前继续

private void dgvTracks_CellDoubleClick(object sender, DataGridViewCellEventArgs e) 
    { 
     PlayFiles(e.RowIndex); 
    } 
    public void PlayFiles(int index) 
    { 
     try 
     { 
      int eof = dgvTracks.Rows.Count; 
      for (int i = index; index <= eof; i++) 
      { 
       if (File.Exists(dsStore.Tables["Track"].Rows[i]["Filepath"].ToString())) 
       { 
        PlayFile(dsStore.Tables["Track"].Rows[i]["Filepath"].ToString()); 
        Application.DoEvents(); 
        Thread.Sleep(TimeSpan.FromSeconds(mplayer.AudioLength)); 
       } 
       else 
       { 
        Exception a = new Exception("File doesn't exists"); 
        throw a; 
       } 

      } 

     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message, ex.Message, MessageBoxButtons.OK); 
     } 
    } 
    public void PlayFile(string filename) 
    { 
     mplayer.Open(filename); 
     mplayer.Play(); 
    } 

回答

0

StopClose打新的音频在前之前播放。例如,如果您使用MediaPlayer.Play

using System.Windows.Media; 

MediaPlayer mplayer = new MediaPlayer(); 

public void PlayFile(string filename) 
{ 
    mplayer.Stop(); 
    mplayer.Close(); 
    mplayer.Open(filename); 
    mplayer.Play(); 
} 
1

我假设mplayerSystem.Windows.Media.MediaPlayer一个实例。

您可以订阅MediaPlayer.MediaEnded事件,并使用事件处理程序开始播放下一个文件。您需要将当前播放的索引存储在某处。

... 

int currentPlayIndex = -1; 

... 

mplayer.MediaEnded += OnMediaEnded; 

... 

private void OnMediaEnded(object sender, EventArgs args) 
{ 
    // if we want to continue playing... 
    PlayNextFile(); 
} 

... 

public void PlayNextFile() 
{ 
    PlayFiles(currentPlayIndex + 1); 
} 

public void PlayFiles(int index) 
{ 
    try 
    { 
     currentPlayIndex = -1; 

     int eof = dgvTracks.Rows.Count; 
     for (int i = index; index <= eof; i++) 
     { 
      if (File.Exists(dsStore.Tables["Track"].Rows[i]["Filepath"].ToString())) 
      { 
       currentPlayIndex = i; // <--- save index 

       PlayFile(dsStore.Tables["Track"].Rows[i]["Filepath"].ToString()); 
       Application.DoEvents(); 
       Thread.Sleep(TimeSpan.FromSeconds(mplayer.AudioLength)); 
      } 
      else 
      { 
       Exception a = new Exception("File doesn't exists"); 
       throw a; 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message, ex.Message, MessageBoxButtons.OK); 
    } 
} 
相关问题