Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing random audio in HTML/Javascript

I am trying to figure out how to continuously play random audio sound bites, one after another without having them overlap on an HTML page using jquery. I have code that plays random sound bites on a timer, but sometimes they overlap and sometimes there is a pause in between the sounds. I had looked into ended and other EventListeners but I really have no idea what I am doing. Here is a portion my code:

<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');
            };

Is there a way to just continuously play these sounds bites one after another right after the previous sound plays? FWIW I have many sound bites but I am just showing two above for reference.

like image 898
ajt Avatar asked Dec 01 '25 00:12

ajt


1 Answers

So I dabbled a bit, here's a full pure JavaScript solution.

Should be cross-browser, haven't tested (/lazy). Do tell me if you find bugs though

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'
]);
like image 144
Khez Avatar answered Dec 02 '25 13:12

Khez