JSFiddle - React, Tailwind, and code Playground

by Chinmay Pendharkar

HTML

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