简体   繁体   中英

Automatically play next item in listbox

I'm making a small media player where I add mediafiles to a listbox which works as a playlist for the mediaelement. When I click on an item in the listbox it starts to play. What I would like to do is to make the mediaelement automatically start playing the next song/video in the listbox after the current has ended.

Here's how I add songs to the 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);
            }
        }

and here's how I can click on an item in the listbox and it starts to play

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

Subscribe to the MediaEnded event of the MediaElement or MediaPlayer and then pick the next item from the listbox.

EDIT

How to pick the next item:

  1. The current item's index is in the SelectedIndex property of the ListBox
  2. You can get the next item by adding 1 to the SelectedIndex and checking if the index is still within bounds
  3. Store the new index in a variable that will keep the new index until the item has been played or change the SelectedIndex directly; this will change the SelectedItem and move the selection in the ListBox

The code below hasn't been checked by a compiler!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM