cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-personicon-teamoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External CSS

These stylesheets will be added in this order and before the code you write in the CSS editor. You can also add another Pen here, and it will pull the CSS from it. Try typing "font" or "ribbon" below.

Quick-add: + add another resource

Add External JavaScript

These scripts will run in this order and before the code in the JavaScript editor. You can also link to another Pen here, and it will run the JavaScript from it. Also try typing the name of any popular library.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

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.

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

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

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

<p><strong>Monitor the console</strong> to see actions:</p>

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

<div>
  <h2>Speak &amp; Spell <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>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>Detection scripts (required)</figcaption>
  <pre><code spellcheck=false contenteditable=true>
const supportsES6=function(){try{return new Function("(a=0)=>a"),!0}catch(n){return!1}}();
const 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 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>Usage</figcaption>
  <pre><code spellcheck=false contenteditable=true>
var track1 = {
  path : "https://websemantics.uk/audio/speak-and-spell/alphabet/10.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
};

if (supportsES6) {

  // Optional preload and store
  Audio.preload(track1);

  // Play ondemand
  Audio.play(track1);

  // Fade out
  Audio.fade(track1);

  // Stop (mostly for loops)
  Audio.stop(track1);

}</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>
            
          
!
            
              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;
}
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 {
  box-shadow: 0 4px 8px #000;
  transform: scale(1.15);
}
button.-js-clicked {
  animation: pressed-btn .3s ease-out;
}
@keyframes pressed-btn {
  50% {transform: scale(0.85);}
  100% {transform: scale(1.15);}
}
figure {
  margin: 1rem 0;
  padding: 1rem;
  border: 1px solid #666;
  background-color: #333;
}
figcaption {font-size:larger;}
pre {
  overflow: hidden;
  margin: 0;
}
pre > code {
  overflow-x: scroll;
  display: block;
  padding: 0;
  font-size:1rem;
}
.speak {
  display: flex;
  max-width: 40rem;
  justify-content: space-around;
  flex-wrap: wrap;
  align-content: center;
}
            
          
!
            
              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;
  }
}());


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

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

  // Test AudioContext availability
  if (!window.AudioContext) {
    if (!window.webkitAudioContext) {
      console.log("Web Audio API is not supported");
      return;
    }
    window.AudioContext = window.webkitAudioContext;
  }
  const audioContext = new AudioContext();
  
  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];
      }

      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;
      let p = 0;
      let encoded1, encoded2, encoded3, encoded4;

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

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

      for (let i = 0; i < len; i+=4) {
        encoded1 = lookup[base64.charCodeAt(i)];
        encoded2 = lookup[base64.charCodeAt(i+1)];
        encoded3 = lookup[base64.charCodeAt(i+2)];
        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) {
      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) {
    if (useSessionStorage && !(track.path in sessionStorage)) {
      _fetchAudio(track);
    }
  }

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

      // Safari has issue with at least this:
      track.audioSource.stop();
    }
  }

  function fadeOutAudio(track) {

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

    stopAudio(track);
    _buildTrack(track);
    _getAudio(track);
    _setGain(track);
    track.audioSource.loop = (track.loop == true) || false;
    track.audioSource.start(0, 0); // Possibly add sprite positions?
  }


  // 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) {
  Audio.play(track1);
}
*/

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

// Define track in play call, not reuseable
/*
if (supportsES6) {
  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) {
  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
Close

Asset uploading is a PRO feature.

As a PRO member, you can drag-and-drop upload files here to use as resources. Images, Libraries, JSON data... anything you want. You can even edit them anytime, like any other code on CodePen.

Go PRO

Loading ..................

Console