Luke Smith Luke Smith - 4 years ago 107
Ruby Question

How to reproduce a sound sequence using <audio> tag html5

Actually im new in Ruby on Rails 4 programming with HTML5 ,so here's the question:

How can I reproduce a defined sequence of sounds on a Rails 4 application?
I mean, I need to listen to different sounds reproduced one by one, and between each sound should be a time interval.

Example:

START
< sound 1 >
1 sec of silence
< sound 2 >
1 sec of silence
< sound n >
END


Also I need that the sounds sequence must stat byitself/autoplay.
Help!! :D

Answer Source

A javascript function that takes a list of audio elements and plays them with a pause of 1 second between them.

Included at the end of the html document.

(function() {
  var track1 = document.getElementById('track1');
  var track2 = document.getElementById('track2');
  var track3 = document.getElementById('track3');

  var trackList = [];

  trackList.push(track1);
  trackList.push(track2);
  trackList.push(track3);

  playTracks(trackList); // call the function so it starts playing the 1st song

  ///
  // plays a list of audio elements
  function playTracks(tracks) {
    var curentSong = tracks.shift(); // take out the 1st song in order to play it
    curentSong.play(); // play it
    curentSong.onended = function() { // when it ends
      setTimeout(function() { // wait 1 second
        playTracks(tracks); // play the rest of the list
      }, 1000);
    };
  }
})(); // IIFE so it starts as soon as it's loaded

Another option to start it would be on the window.onload event.

function startMusic() {
  var track1 = document.getElementById('track1');
  var track2 = document.getElementById('track2');
  var track3 = document.getElementById('track3');

  var trackList = [];

  trackList.push(track1);
  trackList.push(track2);
  trackList.push(track3);

  playTracks(trackList); // call the function so it starts playing the 1st song

  ///
  // plays a list of audio elements
  function playTracks(tracks) {
    var curentSong = tracks.shift(); // take out the 1st song in order to play it
    curentSong.play(); // play it
    curentSong.onended = function() { // when it ends
      setTimeout(function() { // wait 1 second
        playTracks(tracks); // play the rest of the list
      }, 1000);
    };
  }
}

// start playing after the page loads
window.onload = startMusic;

The audio elements can be generated by the server.

<audio>
    <source src="<%= $pathOfTheSound %>"></source>
</audio>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download