I would like to make a shuffle button for my audio player like the Roku USB player but don’t have a clue how to do the shuffle part. I have a small number of files in an array/subarray in the code, not pulled from an XML/database (that would be easy) so since this code is sitting on someones desk at Roku could that someone point me in the right direction on this ? thanks.
You just want to randomize the order of entries in an array? The Fisher-Yates shuffle is a good simple algorithm. (This is my own code, not part of the USB player.)
function Shuffle(array as Object) as Void
for i% = array.count()-1 to 1 step -1
j% = Rnd(i% + 1) - 1 ' pick random j
t = array[i%] : array[i%] = array[j%] : array[j%] = t ' swap [i] with [j]
end for
end function
–Mark
Thank you Mark!, I’m going to have to stare at that while to make sense of it, but that what i was looking for - it would take forever to figure that out. Thanks for the link too, theres always a lot to learn with each simple thing.
So I’ve added the shuffle function to my audio player. The audio wont play when the list is shuffled. I know its shuffling because the screen info shows that, its just the audio player wont start. It also wont play when the guts of the Shuffle function are commented out and the list is not shuffled, so i’m wondering about my syntax. It plays fine if shuffle is “off” .
the array is “item”
if sec.Read("shuffle") = "off"
m.audio.SetContentList(item)
end if
if sec.Read("shuffle") = "on"
m.audio.SetContentList(Shuffle(item))
end if
Function Shuffle(item As Object)
for i% = item.count()-1 to 1 step -1
j% = Rnd(i% + 1) - 1 ' pick random j
t = item[i%] : item[i%] = item[j%] : item[j%] = t ' swap [i] with [j]
end for
End Function
Also doesnt work here:
Function Shuffle(item As Object)
'for i% = item.count()-1 to 1 step -1
' j% = Rnd(i% + 1) - 1 ' pick random j
' t = item[i%] : item[i%] = item[j%] : item[j%] = t ' swap [i] with [j]
'end for
End Function
Thanks
Your shuffle function manipulates the array directly, and doesn’t return anything, but your call to shuffle is expecting a return value. Two possible fixes…
- add “Return item” to the end of your Shuffle function
- Call Shuffle(item) prior to calling SetContentList(item)
Well thats why you’re theEndless and I’m not.
I did your solution #1, it took a whole ten seconds to fix including the sideloading.
Thank you! I knew it had to be simple but I wouldn’t have seen that no matter how long i looked.
You made a mistake. It returns less (n-1) elements than the original array.
