0

When adding more files to my playlist, it throws an out of bounds exception. It doesn't throw the exception when you load files the first time around. I think the problem is because the playlist.SelectedIndex needs a value placed into it. Any ideas?

private void mediaPlayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
    if (e.newState == 1)
    {
        if (playlist.SelectedIndex < playlist.Items.Count)
        {
            BeginInvoke(new Action(() => {    
                if ((playlist.SelectedIndex + 1) < playlist.Items.Count)
                {
                     mediaPlayer.URL = paths[playlist.SelectedIndex];
                     playlist.SelectedIndex++;
                }
                else 
                {
                    mediaPlayer.Ctlcontrols.stop();
                }
            }));
        }
    }
}

private void load_button_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Multiselect = true;
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        files = ofd.SafeFileNames;
        paths = ofd.FileNames;
    }

    for (int i =0; i< files.Length; i++)
    {
        playlist.Items.Add(files[i]);
    }

    playlist.SelectedIndex = 0;

}
Palle Due
  • 5,929
  • 4
  • 17
  • 32
user8639588
  • 43
  • 1
  • 1
  • 7
  • 1
    Questions. 1.) At what line is the exception thrown exactly? 2.) Where is `playlist` instantiated? I think it has to do with instantiation of `playlist`. The first time it sets its size to the given files. When trying to add, it can't because its initial size is less. – Mike de Klerk Oct 07 '19 at 11:16
  • Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – xdtTransform Oct 07 '19 at 11:17
  • playlist is the name I gave the listbox instantiated in the designer. exception throws on ' mediaPlayer.URL = paths[playlist.SelectedIndex];' – user8639588 Oct 07 '19 at 11:30
  • ps i get that arrays do not grow. the playlist.items is a list, not an array – user8639588 Oct 07 '19 at 11:33
  • There is code missing that gets the player activated. So non-zero odds that SelectedIndex can be -1. Note how the event handler has an off-by-one bug, it selects the URL that should have just finished playing. – Hans Passant Oct 07 '19 at 11:34
  • Ah I found the answer. yes- listbox is a list. however the media player also needs the url to locate the file. The code I copied had an array of urls rather than a list or URLs. – user8639588 Oct 07 '19 at 12:54

0 Answers0