Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
<h1>Web Audio API<br>- fetch, store, play <span>(volume, loop, fade-in, fade-out)</span>, stop</h1>

<p>Updating to circumvent, or adapt to, Chrome's requirement:</p>
<blockquote>The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page.</blockquote>

<div>
  <h2>Speak &amp; Spell example <span>(hover prefetches, click plays)</span></h2>
  <p class=speak>

    <button onmouseover="Audio.load(alphabet.zero)" onclick="Audio.play(alphabet.zero);">Zero</button> 
    <button onmouseover="Audio.load(alphabet.one)" onclick="Audio.play(alphabet.one);">One</button> 
    <button onmouseover="Audio.load(alphabet.two)" onclick="Audio.play(alphabet.two);">Two</button> 
    <button onmouseover="Audio.load(alphabet.three)" onclick="Audio.play(alphabet.three);">Three</button> 
    <button onmouseover="Audio.load(alphabet.four)" onclick="Audio.play(alphabet.four);">Four</button> 
    <button onmouseover="Audio.load(alphabet.five)" onclick="Audio.play(alphabet.five);">Five</button> 
    <button onmouseover="Audio.load(alphabet.six)" onclick="Audio.play(alphabet.six);">Six</button> 
    <button onmouseover="Audio.load(alphabet.seven)" onclick="Audio.play(alphabet.seven);">Seven</button> 
    <button onmouseover="Audio.load(alphabet.eight)" onclick="Audio.play(alphabet.eight);">Eight</button> 
    <button onmouseover="Audio.load(alphabet.nine)" onclick="Audio.play(alphabet.nine);">Nine</button> 
    <button onmouseover="Audio.load(alphabet.ten)" onclick="Audio.play(alphabet.ten);">Ten</button> 
  </p>
</div>


<h2>Exposes methods to play small audio samples upon user interactions.</h2>

<ul>
  <li>Featherweight, compiled &prop; 2.52KB &asymp; 1.02KB gzipped
  <li>Loads audio samples using the Fetch API</li>
  <li>Stores samples into <code>sessionStorage</code> for reuse (available space untested)</li>
  <li>Fetches and plays sample upon demand</li>
  <li>Option to preload a given sample</li>
  <li>Option to loop a sample</li>
  <li>Individual volume and fade-in / fade-out settings</li>
  <li>Errors caught and reported in console.</li>
</ul>

<h2>Monitor the console to see actions:</h2>

<p><button onclick="sessionStorage.clear(); console.clear();">Clear storage and console</button></p>



<h2>Looping</h2>
<p>
  <button onclick="Audio.play(noise)">Noise loop</button>
  <button onclick="Audio.fade(noise)">Fade noise</button>
  <button onclick="Audio.stop(noise)">Stop that bloody racket!</button>

<p><button onclick="Audio.play(track5={path:'https://websemantics.uk/audio/sound.mp3', volume:.125, loop:false});">Example 404 (audio path doesn't exist)</button></p>



<h2>Is the JavaScript no?</h2>


<figure>
  <figcaption>Boolean detection scripts (required)</figcaption>
  <pre><code class=language-javascript spellcheck=false contenteditable=true>var supportsES6=function(){try{return new Function("(a=0)=>a"),!0}catch(n){return!1}}();
var useSessionStorage=function(){try{var e=(new Date).valueOf()+"";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(t){return!1}}();
</code></pre>
</figure>

<figure>
  <figcaption>Google Closure compiled (&prop; 2.52KB &asymp; 1.02KB gzip)</figcaption>
  <pre><code class=language-javascript spellcheck=false contenteditable=true>// Web Audio API - Fetch, store, preload, play (volume, loop), fade, stop - v1.0 MJF @ websemantics.uk
var Audio=function(){function h(a,b){a.audioSource&&d.decodeAudioData(b,function(e){a.audioSource.buffer=e})}function k(a){fetch(a.path).then(function(a){return a.arrayBuffer()}).then(function(b){useSessionStorage&&sessionStorage.setItem(a.path,l.encode(b));return b}).then(function(b){return h(a,b)})["catch"](function(b){return console.log("Fetch "+b,a.path)})}function f(a){a.audioSource&&(clearTimeout(n),a.audioSource.stop())}if(supportsES6){if(!window.AudioContext){if(!window.webkitAudioContext){console.log("Web Audio API is not supported");return}window.AudioContext=window.webkitAudioContext}var d=new AudioContext,n,l=function(){for(var a=new Uint8Array(256),b=0;64&gt;b;b++)a["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(b)]=b;return{encode:function(a){a=new Uint8Array(a);for(var b=a.length,c="",e=0;e&lt;b;e+=3)c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[a[e]&gt;&gt;2],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(a[e]&3)&lt;&lt;4|a[e+1]&gt;&gt;4],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(a[e+1]&15)&lt;&lt;2|a[e+2]&gt;&gt;6],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[a[e+2]&63];2===b%3?c=c.substring(0,c.length-1)+"=":1===b%3&&(c=c.substring(0,c.length-2)+"==");return c},decode:function(b){var e=b.length,c=.75*b.length,d=0;"="===b[b.length-1]&&(c--,"="===b[b.length-2]&&c--);for(var f=new ArrayBuffer(c),m=new Uint8Array(f),g=0;g&lt;e;g+=4){c=a[b.charCodeAt(g)];var h=a[b.charCodeAt(g+1)];var k=a[b.charCodeAt(g+2)];var l=a[b.charCodeAt(g+3)];m[d++]=c&lt;&lt;2|h&gt;&gt;4;m[d++]=(h&15)&lt;&lt;4|k&gt;&gt;2;m[d++]=(k&3)&lt;&lt;6|l&63}return f}}}();return{load:function(a){!useSessionStorage||a.path in sessionStorage||k(a)},play:function(a){f(a);a.audioSource=d.createBufferSource();a.gainNode=d.createGain();a.audioSource.connect(a.gainNode);a.gainNode.connect(d.destination);a.canFade=!0;a:{if(useSessionStorage){var b=sessionStorage.getItem(a.path);if(null!==b){b=l.decode(b);h(a,b);break a}}k(a)}a.volume=0&lt;=a.volume?a.volume:.5;a.fadeIn&&0&lt;a.fadeIn?(a.gainNode.gain.setValueAtTime(0,d.currentTime),a.gainNode.gain.linearRampToValueAtTime(a.volume,d.currentTime+a.fadeIn)):a.gainNode.gain.value=a.volume;a.audioSource.loop=1==a.loop||!1;a.audioSource.start(0,0)},stop:f,fade:function(a){a.canFade&&a.fadeOut&&0&lt;a.fadeOut?(a.gainNode.gain.setValueAtTime(a.volume,d.currentTime),a.gainNode.gain.linearRampToValueAtTime(0,d.currentTime+a.fadeOut),a.canFade=!1,n=setTimeout(function(){f(a)},1E3*a.fadeOut)):f(a)}}}}();</code></pre>
</figure>


<figure>
  <figcaption>Could be defined inline</figcaption>
  <pre><code class=language-markup spellcheck=false contenteditable=true>&lt;button 
  onclick="Audio.play({path:'path/to/sample.mp3'});"&gt;
    Sample
&lt;/button&gt;</code></pre>
</figure>


<figure>
  <figcaption>With preload is better</figcaption>
  <pre><code class=language-markup spellcheck=false contenteditable=true>&lt;button 
  onmouseover="Audio.load(sample = {path:'path/to/sample.mp3'})" 
  onclick="Audio.play(sample);"&gt;
    Sample
&lt;/button&gt;</code></pre>
</figure>


<figure>
  <figcaption>But best defined in JavaScript</figcaption>
  <pre><code class=language-javascript spellcheck=false contenteditable=true>var sample = {
  path : "path/to/sample.mp3",

  volume : 0.5,  // is default, may be omitted

  loop : false, // false is default, may be omitted
  fadeIn: 0.5,   // time in seconds, 0 is default, may be omitted
  fadeOut: 0.3   // time in seconds, 0 is default, may be omitted
};</code></pre>
</figure>


<figure>
  <figcaption>And attached to the button via events</figcaption>
  <pre><code class=language-markup spellcheck=false contenteditable=true>&lt;button id=btn_sample&gt;Sample&lt;/button&gt;</code></pre>
  <pre><code class=language-javascript spellcheck=false contenteditable=true>if (supportsES6) {
  const btn_sample = document.querySelector("#btn_sample);
  if (btn_sample) {
    btn_sample.addEventListener("mouseover", () => {
      Audio.load(sample);
    }, {once:true});
    btn_sample.addEventListener("click", () => {
      Audio.play(sample);
    }, false);
  }
}</code></pre>
</figure>


<h2>To do</h2>
<ul>
  <li>Issue with Safari.</li>
  <li>Use a sound sprite rather than multiple small sound files?</li>
  <li>Use an end of fade event, if it exists.</li>
</ul>
              
            
!

CSS

              
                body {
  background-color: #1a1a1a;
  color: #fff;
  font-family: sans-serif;
  line-height: 1.5;
  margin: 1rem;
  position: relative;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg width='1200' height='256' viewBox='0 0 1200 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cdefs%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.4'%3E%3C/feTurbulence%3E%3C/filter%3E%3C/defs%3E%3Crect height='256' width='1200' filter='url(%23noise)' opacity='.15'/%3E%3C/svg%3E");
  background-attachment: fixed;
}
blockquote {font-style: italic;}
h1, h2 {font-weight: 100;}
h2 {margin-top: 3rem;}
h1 > span,
h2 > span {font-size: medium;}
h1 + p {font-size:larger;}
button {
  border: 2px solid #000;
  border-radius: 50px;
  padding: .5rem 1rem;
  font-size: inherit;
  font-weight: bold;
  margin: .5rem .5rem;
  transition: all .3s ease-out;
}
.speak button {
  background-image: radial-gradient(ellipse at center, #FDE900 20% ,#FD8515 80%);
  border-color: #FD8515;
  width: 5.5rem;
  height: 5.5rem;
  box-shadow: 0 4px 4px #000;
}
button:hover,
button:focus {
  box-shadow: 0 4px 8px #000;
  transform: scale(1.15);
  outline: 0;
}
button::-moz-focus-inner { 
  border: 0; 
}
button.-js-clicked {
  animation: pressed-btn .3s ease-out;
}
@keyframes pressed-btn {
  50% {transform: scale(0.85);}
  100% {transform: scale(1.15);}
}
figure {
  max-width: 40rem;
  margin: 2rem auto;
  padding: 1rem;
  border: 1px solid #000;
  background-color: #333;
}
figcaption {font-size:larger;}

ul {
  max-width:34rem;
  margin: 1rem auto;
}
h1, h2, p {
  text-align:center;
}
.speak {
  display: flex;
  max-width: 40rem;
  justify-content: space-around;
  flex-wrap: wrap;
  align-content: center;
  margin:0 auto;
}
              
            
!

JS

              
                var supportsES6 = (function() {
  try {
    new Function("(a = 0) => a"); // Not so evil eval?
    return true;
  }
  catch (err) {
    console.log("No ES6");
    return false;
  }
}());


// button click animation classes
var btn_clicked = (function () {

  "use strict";
  if (!supportsES6) {return}

  const buttons = document.querySelectorAll("button");
  for (const btn of buttons) {

    btn.addEventListener("click", _ => {

      btn.addEventListener("animationend", _ => {
        btn.classList.remove("-js-clicked");
      }, {once: true});

      btn.classList.add("-js-clicked");
    });

  }
}());


var useSessionStorage = (function () {
  try {
    var mod = new Date().valueOf() + "";
		localStorage.setItem(mod, mod);
		localStorage.removeItem(mod);
		return true;
  } catch (e) {
    console.log("No sessionStorage");
    return false;
  }
}());

var hasWebAudio = (function () {
  return window.AudioContext ? true : false;
}());


// Web Audio API - Fetch, store, play (volume, loop), stop - v1.1 MJF @ websemantics.uk
var Audio = (function () {

  "use strict";
  if (!supportsES6) {return}
  if (!hasWebAudio) {return}

  // Cannot be set prior to a user action due to Chrome's rule:
  // "The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page."
  let audioContext;

  const instantiateAudioContext = _ => {
    if (audioContext) return;
    audioContext = new AudioContext();
  };

  // // Test AudioContext availability
  // if (!window.AudioContext) {
  //   if (!window.webkitAudioContext) {
  //     console.log("Web Audio API is not supported");
  //     return;
  //   }
  //   window.AudioContext = window.webkitAudioContext;
  // }

  let TO; // a setTimeout used to stop a faded out sound. 

  // base64-arraybuffer - https://github.com/niklasvh/base64-arraybuffer - 2012 Niklas von Hertzen - Licensed under the MIT license.
  const b64_buffer = (function(){

    // Converts arraybuffer to base64 and vice-versa

    const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    // Use a lookup table to find the index.
    const lookup = new Uint8Array(256);
    for (let i = 0; i < chars.length; i++) {
      lookup[chars.charCodeAt(i)] = i;
    }

    const encode = (arraybuffer) => {
      const bytes = new Uint8Array(arraybuffer);
      const len = bytes.length;
      let base64 = "";

      for (let i = 0; i < len; i += 3) {
        base64 += chars[bytes[i] >> 2];
        base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
        base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
        base64 += chars[bytes[i + 2] & 63];
      }

      // Add padding
      if ((len % 3) === 2) {
        base64 = base64.substring(0, base64.length - 1) + "=";
      } else if (len % 3 === 1) {
        base64 = base64.substring(0, base64.length - 2) + "==";
      }

      return base64;
    };

    const decode =  (base64) => {
      const len = base64.length;
      let bufferLength = base64.length * 0.75;

      // Remove padding
      if (!base64[base64.length - 1] === "=") {
        bufferLength--;
        if (base64[base64.length - 2] === "=") {
          bufferLength--;
        }
      }

      const arraybuffer = new ArrayBuffer(bufferLength);
      const bytes = new Uint8Array(arraybuffer);

      let p = 0;

      for (let i = 0; i < len; i += 4) {
        const encoded1 = lookup[base64.charCodeAt(i)];
        const encoded2 = lookup[base64.charCodeAt(i + 1)];
        const encoded3 = lookup[base64.charCodeAt(i + 2)];
        const encoded4 = lookup[base64.charCodeAt(i + 3)];

        bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
        bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
        bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
      }

      return arraybuffer;
    };

    return {
      encode: encode,
      decode: decode
    }

  }());



  function _populateAudioContext(track, buffer) {

    if (!track.audioSource) return;
    audioContext.decodeAudioData(buffer, decodedData => {
      track.audioSource.buffer = decodedData;
    });
  }

  function _fetchAudio(track) {

    fetch(track.path)
    .then(response => response.arrayBuffer())
    .then(buffer => {

      if (useSessionStorage) {

        // Convert to Base64 and stuff into sessionStorage for reuse.
        // No check made for available space! Keep samples small, or do a check.
        sessionStorage.setItem(track.path, b64_buffer.encode(buffer));
        console.log("Fetched & stored in sessionStorage: ", track.path);
      }

      return buffer;

    })
    .then(buffer => _populateAudioContext(track, buffer))
    .catch(err => console.log("Fetch " + err,  track.path));
  }

  function preloadAudio(track) {

    // instantiateAudioContext();

    if (useSessionStorage && !(track.path in sessionStorage)) {
      _fetchAudio(track);
    }
  }

  function stopAudio(track) {

    instantiateAudioContext();

    if (track.audioSource) {
      clearTimeout(TO);

      // Using disconnect() as replacement for stop() to try to support Safari
      // https://stackoverflow.com/questions/32563298/audiocontext-issue-with-safari
      // track.audioSource.stop();
      track.audioSource.disconnect();

    }
  }

  function fadeOutAudio(track) {

    instantiateAudioContext();

    if (track.canFade && track.fadeOut && track.fadeOut > 0) {

      track.gainNode.gain.setValueAtTime(track.volume, audioContext.currentTime);
      track.gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + track.fadeOut);

      track.canFade = false;

      TO = setTimeout(() => {
        stopAudio(track);
      }, track.fadeOut * 1000);

    } else {
      stopAudio(track);
    }
  }

  function _buildTrack(track) {
    track.audioSource = audioContext.createBufferSource();
    track.audioSource.ended = function () {
      // stopAudio(track);
      console.log("Ended: ", track.path);
    };
    track.gainNode = audioContext.createGain();
    track.audioSource.connect(track.gainNode);
    track.gainNode.connect(audioContext.destination);
    track.canFade = true; // used to prevent fadeOut firing twice
  }

  function _getAudio(track) {

    if (useSessionStorage) {

      const b64 = sessionStorage.getItem(track.path);
      if (b64 !== null) {
        const buffer =  b64_buffer.decode(b64);
        console.log("From sessionStorage: ", track.path);
        _populateAudioContext(track, buffer);
        return;
      }
    }

    _fetchAudio(track);
  }

  function _setGain(track) {

    track.volume = (track.volume >= 0) ? track.volume : 0.5;

    if (track.fadeIn && track.fadeIn > 0) {

      track.gainNode.gain.setValueAtTime(0, audioContext.currentTime);
      track.gainNode.gain.linearRampToValueAtTime(track.volume, audioContext.currentTime + track.fadeIn);

    } else {
      track.gainNode.gain.value = track.volume;
    }
  }

  function playAudio(track) {

    instantiateAudioContext();

    stopAudio(track);
    _buildTrack(track);
    _getAudio(track);
    _setGain(track);
    track.audioSource.loop = (track.loop && track.loop == true) || false;
    track.audioSource.start(); // Possibly add sprite positions?
    // console.log("playing: ", track.audioSource);
  }


  // Expose functions:
  return {
    load : preloadAudio,
    play : playAudio,
    stop : stopAudio,
    fade : fadeOutAudio
  }

}());

// Note: Using cross-domain samples requires setting .htaccess to:
// Header set Access-Control-Allow-Origin "*"

var noise = {
  path: "https://websemantics.uk/audio/noise.6.wav",
  volume: 0.2, // 0 - 1
  loop: true,
  fadeIn: 0.5, // time in seconds
  fadeOut: 1.3 // time in seconds
}

// USAGES:

// Predefine track in JS
/*
var track1 = {
  path : "https://websemantics.uk/audio/speak-and-spell/alphabet/0.mp3"
};
if (supportsES6) {
  // requires user gesture
  Audio.play(track1);
}
*/

// Define track in play call, which may be reused
/*
if (supportsES6) {
  // requires user gesture
  Audio.play(track2 = {
    path : "https://websemantics.uk/audio/speak-and-spell/alphabet/1.mp3",
    volume : 0.125
  });
  setTimeout(() => {
    // requires user gesture
    Audio.play(track2);
  },1000);
}
*/

// Define track in play call, not reuseable
/*
if (supportsES6) {
  // requires user gesture
  Audio.play({
    path : "https://websemantics.uk/audio/speak-and-spell/alphabet/2.mp3",
    volume : 0.125,
    loop : false
  });
}
*/

// Predefine looping track

// var noise = {
//   path : "https://websemantics.uk/audio/noise.5.mp3",
//   volume : 0.125,
//   loop : true
// };


// Define track and pre-load audio to play later
var track4 = {
  path : "https://websemantics.uk/audio/speak-and-spell/alphabet/4.mp3",
  volume : 0.125
}
if (supportsES6) {
  // requires user gesture
  // Audio.load(track4);
  // Audio.play(track4);
}


// Speak & Spell audio samples - http://www.maximporges.com/2011/10/08/speak-and-spell-samples/

var alphabet = {
  zero : {
    path: "https://websemantics.uk/audio/speak-and-spell/alphabet/0.mp3",
    volume: 0.125
  },
  one : {
    path: "https://websemantics.uk/audio/speak-and-spell/alphabet/1.mp3",
    volume: 0.125
  },
  two : {
    path: "https://websemantics.uk/audio/speak-and-spell/alphabet/2.mp3",
    volume: 0.125
  },
  three : {
    path: "https://websemantics.uk/audio/speak-and-spell/alphabet/3.mp3",
    volume: 0.125
  },
  four : {
    path: "https://websemantics.uk/audio/speak-and-spell/alphabet/4.mp3",
    volume: 0.125
  },
  five : {
    path: "https://websemantics.uk/audio/speak-and-spell/alphabet/5.mp3",
    volume: 0.125
  },
  six : {
    path: "https://websemantics.uk/audio/speak-and-spell/alphabet/6.mp3",
    volume: 0.125
  },
  seven : {
    path: "https://websemantics.uk/audio/speak-and-spell/alphabet/7.mp3",
    volume: 0.125
  },
  eight : {
    path: "https://websemantics.uk/audio/speak-and-spell/alphabet/8.mp3",
    volume: 0.125
  },
  nine : {
    path: "https://websemantics.uk/audio/speak-and-spell/alphabet/9.mp3",
    volume: 0.125
  },
  ten : {
    path: "https://websemantics.uk/audio/speak-and-spell/alphabet/10.mp3",
    volume: 0.125
  }
}
              
            
!
999px

Console