使用复选框进行随机播放功能

时间:2015-06-24 10:43:47

标签: c# .net checkbox shuffle

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

继承我的事件,该事件在赛道结束时自动调用:

// 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#的新手,我只是不知道如何整合播放器在曲目结束后播放随机曲目。

1 个答案:

答案 0 :(得分:2)

您可以使用Random类创建随机值。

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决定选择随机数或下一首曲目