如何使用<audio>标签html5重现声音序列

时间:2015-12-29 15:44:24

标签: javascript ruby html5 ruby-on-rails-4 audio

实际上我是使用HTML5进行Ruby on Rails 4编程的新手,所以这就是问题:

如何在Rails 4应用程序上重现已定义的声音序列? 我的意思是,我需要听一个接一个地再现的不同声音,并且每个声音之间应该是一个时间间隔。

示例:

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

另外我需要声音序列必须通过自身/自动播放。 救命!! :d

1 个答案:

答案 0 :(得分:0)

一个javascript函数,它会获取 audio 元素的列表,并在它们之间以1秒的间隔播放它们。

包含在html文档的末尾。

(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

启动它的另一个选择是window.onload事件。

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;

音频元素可以由服务器生成。

<audio>
    <source src="<%= $pathOfTheSound %>"></source>
</audio>