自动播放列表框中的下一个项目

时间:2012-05-07 13:30:40

标签: c# wpf listbox playlist

我正在制作一个小型媒体播放器,我将媒体文件添加到列表框中,该列表框用作媒体元素的播放列表。当我点击列表框中的某个项目时,它就会开始播放。我想做的是让媒体元素在当前结束后自动开始播放列表框中的下一首歌曲/视频。

以下是我如何将歌曲添加到列表框中:

        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Multiselect = true;

        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            foreach (string file in ofd.FileNames)   
            {
                FileInfo fileName = new FileInfo(file);                   
                listBox.Items.Add(fileName);
            }
        }

以下是我如何点击列表框中的项目并开始播放

        private void Button_Click(object sender, RoutedEventArgs e)
    {
        System.Windows.Controls.Button prevButton = player.Tag as System.Windows.Controls.Button;
        System.Windows.Controls.Button button = sender as System.Windows.Controls.Button;
        FileInfo fileInfo = button.DataContext as FileInfo;

        // If a file is playing, stop it

        if (prevButton != null)
        {
            player.Tag = null;
            player.Stop();
            prevButton.Background = Brushes.White;

            // if the one thats playing is the one that was clicked -> don't play it

            if (prevButton == button)
                return;
        }

        // Play the one that was clicked

        player.Tag = button;
        player.Source = new Uri(fileInfo.FullName);
        player.Play();
    }

1 个答案:

答案 0 :(得分:0)

订阅MediaElement或MediaPlayer的MediaEnded事件,然后从列表框中选择下一个项目。

修改

如何选择下一个项目:

  1. 当前项的索引位于ListBox的SelectedIndex属性
  2. 您可以通过向SelectedIndex添加1并检查索引是否仍然在范围内来获取下一个项目
  3. 将新索引存储在一个变量中,该变量将保留新索引直到项目已播放或直接更改SelectedIndex;这将更改SelectedItem并移动ListBox中的选择
  4. 编译器未检查下面的代码!

    private int currentSongIndex = -1;
    
    void Player_MediaEnded(object sender, EventArgs e)
    {
        if(currentSongIndex == -1)
        {
            currentSongIndex = listBox.SelectedIndex;
        }
        currentSongIndex++;
        if(currentSongIndex < listBox.Items.Count)
        {
            player.Play(listBox.Items[currentSongIndex]);
        }
        else
        {
            // last song in listbox has been played
        }
    }