How to seamlessly loop sound with web audio api How to seamlessly loop sound with web audio api google-chrome google-chrome

How to seamlessly loop sound with web audio api


Took a night of research but i finally found the simplest solution:

<script type="text/javascript">    //this is the webaudio loooooppppppp    //enter url in the next line    var url  = 'hoodie_robot_clipped.wav';    /* --- set up web audio --- */    //create the context    var context = new AudioContext();    //...and the source    var source = context.createBufferSource();    //connect it to the destination so you can hear it.    source.connect(context.destination);    /* --- load buffer ---  */    var request = new XMLHttpRequest();    //open the request    request.open('GET', url, true);     //webaudio paramaters    request.responseType = 'arraybuffer';    //Once the request has completed... do this    request.onload = function() {        context.decodeAudioData(request.response, function(response) {            /* --- play the sound AFTER the buffer loaded --- */            //set the buffer to the response we just received.            source.buffer = response;            //start(0) should play asap.            source.start(0);            source.loop = true;        }, function () { console.error('The request failed.'); } );    }    //Now that the request has been defined, actually make the request. (send it)    request.send();</script>


For those that might not be using wav's and don't care about perfectly seamless... using HTMLMediaElement.loop makes it super simple

  var myAudio = document.getElementById('my-audio');  var play = document.getElementById('play');  var pause = document.getElementById('pause');  // set loop  myAudio.loop = true;  // associate functions with the 'onclick' events  play.onclick = playAudio;  pause.onclick = pauseAudio;  function playAudio() {    myAudio.play();  }  function pauseAudio() {    myAudio.pause();  }
<audio id="my-audio" src="http://static1.grsites.com/archive/sounds/medical/medical006.mp3"></audio><button id="play">PLAY</button><button id="pause">PAUSE</button>