<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>
JavaScript
var context;
var url = "https://www.dropbox.com/s/xefnsktizsadwiw/Always%20In%20My%20Head%20-%20Coldplay.mp3?dl=0";
var source = null;
var myAudioBuffer = null;
function initContext() {
try {
context = new webkitAudioContext();
}
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;
});
}
request.send();
}
function playSound() {
source = context.createBufferSource();
source.buffer = myAudioBuffer;
source.connect(context.destination);
source.start();
}
function stopSound() {
if (source) {
source.stop();
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.