Reputation: 647
I use the Fisher–Yates shuffle for my music-player, however when you play the previous song it's also a random song from the list. So, I added a list that saves the played songs PlayedSongs
. It remembers all songs that were played. How do I play these songs backwards and forwards? If I would go back 3 songs, and then go forward again, it would still be the song that was on number 2. Yet thinking of this algorithm gives me a headache and I can't get it right. Here's what I have.
Again to be clear: I want a shuffle that can play forwards and backwards. When playing backwards all the songs had to be played recently in order. (It's temporary so this list gets cleared on exit).
This if-statement is from another method that normally plays songs and checks if Shuffle is enabled:
//after song was played
if (ShuffleIsOn)
{
ShuffledSongIndexes.Remove(ShuffledSongIndexes.FirstOrDefault());
PlayedSongs.Add(song);
}
Then:
public List<Song> PlayedSongs = new List<Song>();
public int CurrentShuffleIndex = 0;
public void PlayPreviousSongs()
{
PlayedSongs.Reverse();
CurrentShuffleIndex++;
try
{
MediaElement.Source = new Uri(PlayedSongs[CurrentShuffleIndex].FullFileName);
}
catch (ArgumentOutOfRangeException)
{
MediaElement.Source = new Uri(PlayedSongs[CurrentShuffleIndex - 1].FullFileName);
}
MediaElement.Play();
PlayedSongs.Reverse();
}
public void PlayNextSongs()
{
CurrentShuffleIndex++;
MediaElement.Source = new Uri(PlayedSongs[CurrentShuffleIndex].FullFileName);
MediaElement.Play();
}
I haven't found anything on the internet about this, does anyone know how to do this? Thanks
Upvotes: 1
Views: 82
Reputation: 1909
There is no need to reverse the list. Add a bool like: PlayForward, and if it's true then index will increment by 1, otherwise decrement by 1, like:
CurrentIndex += (PlayForward ? 1 : -1)
Also, there is a way u can make ur life easier. Don't change the song whenever u change the index. Instead, combine the process like:
int _CurrentIndex;
public int CurrentIndex
{
get => _CurrentIndex;
set
{
if (value != _CurrentIndex)
{
_CurrentIndex = value;
MediaElement.Source = new Uri(PlayedSongs[CurrentIndex].FullFileName);
MediaElement.Play();
}
}
}
Don't forget to check the bounds too!
Upvotes: 1