Getting Started with Web Audio

The Web Audio API is a JavaScript based API for sound synthesis and processing in web applications. It is compatible to most browsers and can thus be used on almost any device. This makes it a powerful tool in many areas. In the scope of this introduction it is introduced as a means for data sonification with web-based data APIs and for interactive sound examples. Read the W3C Candidate Recommendation for an in-depth documentation.


Autoplay Policy

New browser versions come with an autoplay policy to prevent websites from playing sound on load. To enable the sound, one needs to "Create or resume context from inside a user gesture" (read more http://udn.realityripple.com/docs/Web/API/Web_Audio_API/Best_practices). This has not been implemented in all examples on this website. One way to do this is, is calling the following function from a button:

function startAudio()
{
  AudioContext.resume()
}

The Sine Example

The following Web Audio example features a simple sine wave oscillator with frequency control and a mute button:

Sine Example

Sine Example.

Frequency


Code

Building Web Audio projects involves three components:

  • HTML for control elements and website layout

  • CSS for website appearance

  • JavaScript for audio processing

Since HTML is kept minimal, the code is compact but the GUI is very basic.

../Computer_Music_Basics/webaudio/sine_example/sine_example.html (Source)

<!doctype html>
<html>

<head>
  <title>Sine Example</title>

  <!-- embedded CSS for slider appearance -------------------------------------->

  <style>
  /* The slider look */
  .minmalslider {
    -webkit-appearance: none;
    appearance: none;
    width: 100%;
    height: 25px;
    background: #d3d3d3;
    outline: none;
  }
  </style>
</head>

<!-- HTML control elements  --------------------------------------------------->

<blockquote style="border: 2px solid #122; padding: 10px; background-color: #ccc;">

  <body>
    <p>Sine Example.</p>
    <p>
      <button onclick="play()">Play</button>
      <button onclick="stop()">Stop</button>
      <span>
        <input  class="minmalslider"  id="pan" type="range" min="10" max="1000" step="1" value="440" oninput="frequency(this.value);">
        Frequency
      </span>
    </p>
  </body>

</blockquote>


<!-- JavaScript for audio processing ------------------------------------------>

  <script>

    var audioContext = new window.AudioContext
    var oscillator = audioContext.createOscillator()
    var gainNode = audioContext.createGain()

    gainNode.gain.value = 0

    oscillator.connect(gainNode)
    gainNode.connect(audioContext.destination)

    oscillator.start(0)

    // callback functions for HTML elements
    function play()
    {
      gainNode.gain.value = 1
    }
    function stop()
    {
      gainNode.gain.value = 0
    }
    function frequency(y)
    {
      oscillator.frequency.value = y
    }

  </script>
</html>