带复选框的随机播放功能

Shuffle Function with Checkbox

我需要一个复选框来激活或停用播放列表(数据表)中曲目的随机播放。如果复选框被选中并且播放曲目结束,下一个随机曲目应该自动开始播放。

这是我的事件,当曲目结束时自动调用:

// This event is automatically called when a track has ended
private void mePlayer_MediaEnded(object sender, RoutedEventArgs e)
{
    // Check, if the the (last calculated) Index is in the datagrid range
    // -1 is used, cause the indexes starts by 0 not 1
    if (newIndex >= (dgPlayList.Items.Count - 1)) 
    {
        // If the end of the datagrid is reached, set index to 0 for playing the first track
        newIndex = 0;
    }
    else
    {
        // Is there a following track in the datagrid, then use the next calculated index
        newIndex += 1;
    }
    Console.WriteLine("Set index to: " + newIndex);

    // Tell the media player to use the calculated nexIndex
    mePlayer.Source = new Uri(playList.Rows[newIndex]["Dateiname"].ToString());
    lblFileName.Content = getFileName(playList.Rows[newIndex]["Dateiname"].ToString());

    // Starts to play and set it to play
    mePlayer.Play();
    isPlaying = true;        
}

我是 C# 的新手,我只是不知道如何集成播放器在曲目结束后播放随机曲目。

您可以使用 Random class 创建一个随机值。

define a Random variable outside the function.

Random r = new Random();

并像这样使用它

if (cb_Shuffle.IsChecked == true)
{
    newIndex = r.Next(dgPlayList.Items.Count);
}
else
{
    if (newIndex >= (dgPlayList.Items.Count - 1))
    {
        // If the end of the datagrid is reached, set index to 0 for playing the first track
        newIndex = 0;
    }
    else
    {
        // Is there a following track in the datagrid, then use the next calculated index
        newIndex += 1;
    }
}

newIndex将是一个小于dgPlayList.Items.Count

的非负数

你应该check if the checkbox is checked or not决定选择随机数还是下一首曲目