Skip to content

Instantly share code, notes, and snippets.

@uupaa
Created September 15, 2015 13:26
Show Gist options
  • Save uupaa/2710922bcf0171dcda78 to your computer and use it in GitHub Desktop.
Save uupaa/2710922bcf0171dcda78 to your computer and use it in GitHub Desktop.
WebAudio createMediaElementSource example

WebAudio createMediaElementSource を使用すると、<audio> を音源として利用することが可能です。Chrome, iOS 7++ で動作します。

<p>createMediaElementSource demo</p>
<audio src="mad.max.m4a"></audio>

<script src="a.js"></script>
// a.js
var audioContext = new (window.AudioContext || window.webkitAudioContext)();
var audioNode = document.querySelector("audio");
var playable = false;

if (0) {
  // <audio>
  window.onload = function() {
    document.body.addEventListener("touchstart", function() {
      if (playable) {
        audioNode.play();
      } else {
        audioNode.addEventListener("loadstart",      function(event) { console.log(event.type); });
        audioNode.addEventListener("loadedmetadata", function(event) { console.log(event.type); });
        audioNode.addEventListener("canplay",        function(event) { console.log(event.type);
          playable = true;
          audioNode.play();
        });
        audioNode.load();
      }
    });
  };

} else {
  // WebAudio
  window.onload = function() {
    document.body.addEventListener("touchstart", function() {
      if (playable) {
        audioNode.play();
      } else {
        audioNode.addEventListener("loadstart",      function(event) { console.log(event.type); });
        audioNode.addEventListener("loadedmetadata", function(event) { console.log(event.type); });
        audioNode.addEventListener("canplay",        function(event) { console.log(event.type);
          playable = true;
          audioContext.createMediaElementSource(audioNode).connect(audioContext.destination);
          audioNode.play();
        });
        audioNode.load();
      }
    });
  };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment