JSFiddle - React, Tailwind, and code Playground

by kougiland

HTML

<html><head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="chrome=1">
  <title>Web Audio API: Simple load sound</title>
</head>
<body>
  <input type="file" accept="audio/*">
  <button onclick="playSound()">Start</button>
  <button onclick="stopSound()">Stop</button>
<script>
var context = new window.webkitAudioContext();
var source = null;
var audioBuffer = null;
 
function stopSound() {
  if (source) {
    source.noteOff(0);
  }
}

function playSound() {
  source = context.createBufferSource(); // Global so we can .noteOff() later.
  source.buffer = audioBuffer;
  source.loop = false;
  source.connect(context.destination);
  source.noteOn(0);    
}

function initSound(arrayBuffer) {
  context.decodeAudioData(arrayBuffer, function(buffer) {
    audioBuffer = buffer;
    var buttons = document.querySelectorAll('button');
    buttons[0].disabled = false;
    buttons[1].disabled = false;
  }, function(e) {
    console.log('Error decoding', e);
  }); 
}

document.querySelector('input[type="file"]').addEventListener('change', function(e) {  
  var reader = new FileReader();
  reader.onload = function(e) {
    initSound(e.target.result);
  };
  reader.readAsArrayBuffer(e.target.files[0]);
}, false);
  
// Example loading via xhr2: loadSoundFile('sounds/A220_A880.wav');
function loadSoundFile(url) {
  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.responseType = 'arraybuffer';
  request.onload = function(e) {
    initSound(e.target.response);
  };
  request.send();
}
</script>

</body></html>