在HTML/Javascript中播放随机音频

Playing random audio in HTML/Javascript

本文关键字:播放 随机 音频 Javascript HTML      更新时间:2023-09-26

我想弄清楚如何连续播放随机音频声音片段,一个接一个,而不用在HTML页面上重叠使用jquery。我的代码可以在计时器上播放随机的声音片段,但有时它们会重叠,有时声音之间会有停顿。我已经研究了ended和其他EventListeners,但我真的不知道我在做什么。下面是我代码的一部分:

<html>
    <audio id="audio1">
        <source src="cnn.mp3"></source>
    </audio>
    <audio id="audio2">
        <source src="sonycrackle.mp3"></source>
    </audio>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript">
            $(document).ready(function(){
                    $('audio').each(function(){
                            this.volume = 0.6;
                    });
            var tid = setInterval(playIt, 2000);
            });
            function playIt() {
                    var n = Math.ceil(Math.random() * 2);
                    $("#audio"+n).trigger('play');
            };

是否有一种方法可以在之前的声音播放后一个接一个地连续播放这些声音片段?我有很多声音片段,但我只是展示了上面的两个供参考。

所以我稍微涉水了一下,这里是一个完整的纯JavaScript解决方案。

应该是跨浏览器的,没有测试过(/lazy)。如果你发现了bug一定要告诉我

var collection=[];// final collection of sounds to play
var loadedIndex=0;// horrible way of forcing a load of audio sounds
// remap audios to a buffered collection
function init(audios) {
  for(var i=0;i<audios.length;i++) {
    var audio = new Audio(audios[i]);
    collection.push(audio);
    buffer(audio);
  }
}
// did I mention it's a horrible way to buffer?
function buffer(audio) {
  if(audio.readyState==4)return loaded();
  setTimeout(function(){buffer(audio)},100);
}
// check if we're leady to dj this
function loaded() {
  loadedIndex++;
  if(collection.length==loadedIndex)playLooped();
}
// play and loop after finished
function playLooped() {
  var audio=Math.floor(Math.random() * (collection.length));
  audio=collection[audio];
  audio.play();
  setTimeout(playLooped,audio.duration*1000);
}
// the songs to be played!
init([
  'http://static1.grsites.com/archive/sounds/background/background005.mp3',
  'http://static1.grsites.com/archive/sounds/background/background006.mp3',
  'http://static1.grsites.com/archive/sounds/background/background007.mp3'
]);

一些快速的建议是添加属性preload="auto"到音频元素,并将脚本更改为$(window)。Onload而不是document ready。当html就绪时,Document ready会触发,但当音频和其他资产(如图像)已经加载时,就不一定了。

你也可以考虑在新的Web Audio API中使用AudioBuffer接口,它被描述为"这个接口代表了一个内存驻留的音频资产(用于一次性声音和其他短音频剪辑)",这听起来像是你需要的。我相信你所遇到的部分问题(音频元素的随机暂停/延迟/声音故障)是开发它的原因之一。

阅读更多:

https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html AudioBuffer

不幸的是,只有Chrome和最新的Safari浏览器支持Firefox,预计在未来6个月(左右),还没有关于IE支持的消息。