簡體   English   中英

自動播放列表框中的下一項

[英]Automatically play next item in listbox

我正在制作一個小型媒體播放器,在其中將媒體文件添加到用作媒體元素的播放列表的列表框中。 當我單擊列表框中的項目時,它開始播放。 我想做的是使調解元素在當前播放結束后自動開始播放列表框中的下一首歌曲/視頻。

這是我將歌曲添加到列表框中的方法:

        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();
    }

訂閱MediaElement或MediaPlayer的MediaEnded事件,然后從列表框中選擇下一項。

編輯

如何挑選下一項:

  1. 當前項目的索引位於ListBox的SelectedIndex屬性中
  2. 您可以通過向SelectedIndex加1並檢查索引是否仍在范圍內來獲得下一項
  3. 將新索引存儲在一個變量中,該變量將保留新索引,直到播放該項目或直接更改SelectedIndex為止; 這將更改SelectedItem並在列表框中移動選擇

下面的代碼尚未由編譯器檢查!

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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM