-1

I currently have this js code:

audio.src = path + 'assets/music/'+(Math.floor(Math.random() * songs) +      1)+'.mp3'

And on my website, I have folder assets/music/1.mp3, 2.mp3, 3.mp3, so it picks a random song and it plays the song. (Math.random)

I prefer not to use math.random because sometimes it plays the same track twice and it's annoying.

So any solutions?

Website: http://selen.xyz The javascript code: http://selen.xyz/animate.js

Paul-Jan
  • 16,746
  • 1
  • 63
  • 95

2 Answers2

1

Use Array.prototype.slice() to create a copy of array containing path to file, create empty array songs, call .splice() with Math.floor(Math.random() * copy.length) to retrieve random item from copy , remove selected item from copy , when songs .length is arr original array .length , songs should be filled with pseudo-randomly selected items , set audio element to use items within songs array as src

var arr = [1, 2, 3, 4],
  copy = arr.slice(0),
  songs = [];
while (songs.length < arr.length) {
  var n = Math.floor(Math.random() * copy.length);
  songs[songs.length] = "assets/music/" + copy[n] + ".mp3";
  copy.splice(n, 1)
}
document.writeln(songs.join("<br>"))
guest271314
  • 1
  • 15
  • 104
  • 177
0
  1. Get the last played song ID in localstorage (undefined in the first instance)
  2. Generate a random song id (which does not match the stored value)
  3. Store the new song ID in localstorage

.

var songs = 10,
    last_song_id = localStorage.getItem('last_song_id'),
    song_id;

do {
    song_id = Math.floor(Math.random() * songs) + 1;
} while(last_song_id === song_id);

localStorage.setItem('last_song_id', song_id);

audio.src = path + 'assets/music/' + song_id;
eckymad
  • 1,032
  • 8
  • 6