Web Audio API Basic

by ibroom

HTML

</script>
</head>
 
<body>
  <p>Web audio API example: load a sound file and play/stop it on a button click.</p>
  <button onclick="initcontext()">Init</button>
  <button onclick="loadSound(url)">Load</button>
  <button onclick="playSound()">Play</button>
  <button onclick="stopSound()">Stop</button>
</body>
</html>

JavaScript

var context;
var url = "https://us.cdn.fliplet.com/mediaFolders/445/2be8c5810e18ebe0a93a2235d15ad271003-911-8140.mp3";
var source = null;
var myAudioBuffer = null;

function initcontext() {
    try {
        context = new AudioContext();
    } catch (e) {
        alert('Sorry, your browser does not support the Web Audio API.');
    }
}

function loadSound(url) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'arraybuffer';
    request.onload = function () {
        context.decodeAudioData(request.response, function (buffer) {
            myAudioBuffer = buffer;
            playSound(myAudioBuffer);
        });
    }
    request.send();
}

function playSound(myAudioBuffer) {
    source = context.createBufferSource();
    source.buffer = myAudioBuffer;
    source.connect(context.destination);
    source.start();
}

function stopSound() {
    if (source) {
        source.stop();
    }
}