Loading and playing a sound in a web page (with JavaScript)

Let's look at a simple way to load some sound data into a web page and play it back.

1: we'll get our basic web-page structure in place

<html>
  <head>
    <title>Loading a sound in JavaScript</title>
  </head>

  <body>
    <h1>Loading a sound in JavaScript</h1>

    <div>Status: <span id="status">not loaded</span></div>
    <button>Load</button>
    <button>Play</button>

  </body>
</html>

2: add a function to load a sound file

<html>
  <head>
    <title>Loading a sound in JavaScript</title>
  </head>

  <body>
    <h1>Loading a sound in JavaScript</h1>
<script language="JavaScript"> let audioCtx = null; const load = () => { // AudioContext must be initialized in response to user action: audioCtx = new AudioContext(); const request = new XMLHttpRequest(); // We specify the URL of the sound (on the server) here: request.open("GET", "creativecod.ing/sound/ride-cymbal.wav"); // Retrieve the sound as binary data in a JS ArrayBuffer request.responseType = "arraybuffer"; // When the sound has loaded, just update the status for now: request.onload = function() { document.getElementById('status').innerHTML = 'loaded'; }; // Dispatch the request: request.send(); } </script>
<div>Status: <span id="status">not loaded</span></div> <!-- Trigger our 'load()' function when this button is clicked: --> <button onclick="javascript:load();">Load</button> <button>Play</button> </body> </html>