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

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.



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>

  <title>Sine Example</title>

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

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

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

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

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


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


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

    gainNode.gain.value = 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