Getting a "Value does not fall within the expected range" error when music stops playing

1

In my UWP App I have a ListView with all songs displayed in the Music Library folder. When you click on a song it will play it and move to the next song when the first one stops. All this works great, however when the last song plays and reaches the end I get this error

System.ArgumentException
HResult=0x80070057
Message=Value does not fall within the expected range.
Source=Windows
StackTrace:
at Windows.UI.Xaml.Controls.Primitives.Selector.put_SelectedIndex(Int32 value)

This is the code I have:

private async void objMediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
    {
        mediaElement.Stop();

        if (AudioFilesLV.SelectedIndex <= AudioFilesLV.Items.Count)
        {
            AudioFilesLV.SelectedIndex = AudioFilesLV.SelectedIndex += 1;
            var file = await KnownFolders.MusicLibrary.GetFileAsync(AudioFilesLV.SelectedItem.ToString());
            if (file != null)
            {
                var stream = await file.OpenReadAsync();
                mediaElement.SetSource(stream, file.ContentType);
                mediaElement.Play();
            }
        }

        else
        {
            mediaElement.Stop();
        }
    }

    private void mediaItemList_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }

    private void objMediaPlayer_MediaOpened(object sender, RoutedEventArgs e)
    {
        mediaElement.Play();
    }

The App crashes at this line:

 AudioFilesLV.SelectedIndex = AudioFilesLV.SelectedIndex += 1;

I can't figure out what the problem is. I think it is looking for the next song but there isn't one. So I need to tell the app to stop after the last song plays, but don't know how to do this?

Thanks

EDIT

private async void objMediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
    {
        int LastPlayedIndex;
        LastPlayedIndex = AudioFilesLV.SelectedIndex;
            AudioFilesLV.SelectedIndex = AudioFilesLV.SelectedIndex = 1;
            var file = await KnownFolders.MusicLibrary.GetFileAsync(AudioFilesLV.SelectedItem.ToString());
            if (AudioFilesLV.SelectedIndex < AudioFilesLV.Items.Count && AudioFilesLV.SelectedIndex != LastPlayedIndex)
            {
                var stream = await file.OpenReadAsync();
                mediaElement.SetSource(stream, file.ContentType);
                mediaElement.Play();
            }

        else
        {
            mediaElement.Stop();
        }
    }
c#
uwp
asked on Stack Overflow Jun 6, 2020 by UWP Enthusiast • edited Jun 9, 2020 by UWP Enthusiast

1 Answer

1

Looks like AudioFilesLV.SelectedIndex += 1 is more than AudioFilesLV.Items.Count ? Condition above is "<=", so index may be out of range. Maybe needeed another check, if .SelectedIndex is last in list, and do not increment value in this case?

answered on Stack Overflow Jun 6, 2020 by u1035

User contributions licensed under CC BY-SA 3.0