如何使用<音频>标签html5

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

本文关键字:标签 html5 gt 音频 lt 何使用      更新时间:2023-09-26

实际上,Ruby on Rails 4使用HTML5编程是新的,所以问题是:

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

示例:

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

我还需要声音序列必须自己统计/自动播放。救命!!:D

一个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>