HTML5 Game - Audio Analyzing Audio

Description

Analyzing Audio

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html>
  <head>
    <title>Chapter 3 - Web Audio API</title>
  </head>/*from   ww  w  . j av a  2s.co  m*/

  <body>
    <audio controls onvolumechange="volumeChange();">
        <source src='http://java2s.com/style/demo/your.ogg' type='audio/ogg; codecs=vorbis'>
         <source src='http://java2s.com/style/demo/your.mp3' type='audio/mpeg'>
    </audio>
    <script>
// Pollyfill for AudioContext
(function() {
  window.AudioContext = window.AudioContext || window.webkitAudioContext;
})();

let ele = document.querySelector('audio');
let ctx = new AudioContext();


let analyser = ctx.createAnalyser();
let logger = ctx.createJavaScriptNode(analyser.frequencyBinCount, 1, 1);

let source = ctx.createMediaElementSource(ele);
let volumeControl = ctx.createGainNode();

source.connect(volumeControl);
volumeControl.connect(analyser);
analyser.connect(ctx.destination);

ele.addEventListener('onvolumechange', volumeControl, false);

function volumeChange()  {
  volumeControl.gain.value = ele.volume;
}


function log()  {
  freqData = new Uint8Array(analyser.frequencyBinCount);
  analyser.getByteFrequencyData(freqData);
  for (let i = 0; i < freqData.length; i++) {
    console.log(freqData[i] * ctx.sampleRate / analyser.fftSize);        
  }
}      
      </script>
  </body>
</html>

Related Topic