How to create random audio playlist?

Asked

Viewed 3,185 times

3

I need something like this

function next() 
{ 
Url = new Array; 
Url[0] = "/mp3/001.mp3"; 
Url[1] = "/mp3/002.mp3"; 
Url[2] = "/mp3/003.mp3"; 
Url[3] = "/mp3/004.mp3"; 

Link = Math.floor(Math.random() * Url.length); 

} 


<audio autoplay="autoplay" onended="next()">
<source src="Url[Link]" type="audio/mpeg">
navegador não suporta áudio em HTML5.</audio>

3 answers

5


You came close, missed making the interactions between Javascript and HTML, as well as calling the functions of the element audio.

See in the code below how simple it is:


HTML

<audio id="player">
  O seu navegador não suporta áudio em HTML5.
</audio>


JAVASCRIPT

/* Objects */
var _player = document.getElementById('player');

/* Aplication */
var tracks = [
  '1.mp3',
  '2.mp3',
  '3.mp3',
  '4.mp3',
  '5.mp3'
];

function playNext() {
  var track = tracks[Math.floor(Math.random() * tracks.length)];

  _player.src = track;
  return _player.play();
}

/* Events */
window.addEventListener('load', playNext);
_player.addEventListener('ended', playNext);


You can see working on the link http://codepen.io/caio/pen/smyac, but remember to change the path of the audio files.

  • This underline before the player (_player) it’s a convention?

  • No @Patrick, particularly like to differentiate variables from DOM variables when using Vanilla JS. :)

4

What I find legal in these cases of Random playlist is to remove the already played elements from the array, so it does not risk repeating. And when you empty the array, you populate it back with the original array.

I made an adaptation of code of Caio Tarifa demonstrating the idea: Jsfiddle.

To clone the array is used:

tracks_clone = tracks.slice(0);

With each song played, delete the element:

tracks_clone.splice(randnum, 1);

And before you start playing, check to see if the clone is already empty and popular again in a positive case:

if( tracks_clone.length === 0 ) {
    tracks_clone = tracks.slice(0);
}

HTML

<div id="now"></div>
<audio preload="none" id="player" controls="controls"></audio>
<button id="next">next</button>
<p id="playlist"></p>

JS

var _now = document.getElementById('now'),
    _player = document.getElementById('player'),
    _next = document.getElementById('next'),
    _playlist = document.getElementById('playlist'),
    tracks_clone,
    mp3uri = 'http://www.stephaniequinn.com/Music/',
    tracks = [
        'Commercial%20DEMO%20-%2005.mp3',
        'Commercial%20DEMO%20-%2006.mp3',
        'Commercial%20DEMO%20-%2006.mp3',  
    ];

function playNext() {
    if( tracks_clone.length === 0 ) {
        tracks_clone = tracks.slice(0);
    }
    var randnum = Math.floor(Math.random() * tracks_clone.length);
    var track = tracks_clone[randnum];
    _now.innerHTML = '<b>Random selected</b>: #' + randnum + '<br><b>Playing</b>: ' + decodeURIComponent(track).replace('.mp3','');
    tracks_clone.splice(randnum, 1);
    _playlist.innerHTML = ' - ' + decodeURIComponent(tracks_clone.join('<br> - '));
    _player.src = mp3uri + track;
    return _player.play();
}

function initPlayer() {
    tracks_clone = tracks.slice(0);
    _player.addEventListener('ended', playNext);
    _next.addEventListener('click', playNext, false);
    playNext();
}

window.addEventListener('load', initPlayer);

0

I did it this way, then every time I hit the "next" button it will load a new song

function id(id) {
  return document.getElementById(id)
}

function init() {
  var container = id('fundo-controles');
  var ctr = id('som');
  var play = id('play');
  var pause = document.getElementById('pause');
  var vmais = document.getElementById('vmais');
  var vmenos = document.getElementById('vmenos');
  var mudou = id("proxi");
  if (!Modernizr.audio) {
    container.style.display = 'none';
  } else {
    play.addEventListener('click', function() {
      ctr.play();
      ctr.volume = 1;
    }, false);

    pause.addEventListener('click', function() {
      ctr.pause();
    }, false);

    vmais.addEventListener('click', function() {
      ctr.play();
      ctr.volume += 0.25;

    }, false);
    mudou.addEventListener('click', function() { //usado para passar a musica
      var num = 1; //contador para referencia das musicas
      num += 1;
      if (num == 9) //parametro de comparação se terminou as musicas
        num = 1;
      ctr.pause(); //para a musica que estava tocando
      document.getElementById('aqui').src = "musicas/" + num + ".mp3"; //muda o 'src' para outra musica
      ctr.load(); ///Muito necessario para poder carregar a musica nova
      ctr.play();


    }, false);

    vmenos.addEventListener('click', function() {
      ctr.play();
      ctr.volume -= 0.25;
    }, false);
  };
}
window.onload = init;
HTML
<body>

  <h1> AUDIO HTML5</h1>
  <section>
    <audio id="som">
      <source src="musicas/1.mp3" type="audio/mpeg" id="aqui">

        <p>Seu navegador não suporta o elemento da HTML5.
          <br>Faça <a href="som.zip">download de som.zip</a>
        </p>
    </audio>
    <div id="fundo-controles">
      <input type="image" src="javaaudio/play.png" alt="play" id="play">
      <input type="image" src="javaaudio/pause.png" alt="pause" id="pause">
      <input type="image" src="javaaudio/vmais.png" alt="Volume+" id="vmais">
      <input type="image" src="javaaudio/vmenos.png" alt="volume-" id="vmenos">
      <input type="button" value="proximo" id="proxi">
    </div>

  </section>



</body>

  • 1

    That’s an answer?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.