1

What I need is a checkbox to activate or deactivate the random playback from tracks in a playlist (datatable). If the checkbox is checked and a playing track ended the next random track should start playing automatically.

Heres my event which is automatically called when a track has ended:

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

Im pretty new to C# and I just don't know how to integrate that the player plays a random track after a track has ended.

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
jwi
  • 1,116
  • 1
  • 18
  • 38

1 Answers1

2

You can use Random class to create a random value.

define a Random variable outside the function.

Random r = new Random();

and use it like this

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

then newIndex will be a non-negative number less than dgPlayList.Items.Count

you should check if the checkbox is checked or not to decide choosing random number or the next track

Community
  • 1
  • 1
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
  • Thanks! How do I integrate the `newIndex = r.Next(dgPlayList.Items.Count);` with a checkbox in the above mentioned event? I've created a checkbox in the form and then tried to add something like `if (checkbox_shuffle.checked) ...` - but I alway get an error `Identifier expected; "checked" is a keyword"`.. I want to set the newIndex with the random number only if the checkbox is checked. – jwi Jun 24 '15 at 10:57
  • it should be `Checked` not `checked` – Hamid Pourjam Jun 24 '15 at 10:59
  • 1
    It is `if (cb_Shuffle.IsChecked == true)` and it works like charm! Thanks for your help! :) – jwi Jun 24 '15 at 11:09