<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="../js/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="example">
<audio id="player" class="hideIfNoApi" controls="controls" src="http://ianreah.apphb.com/sounds/movement%20proposition.mp3" crossorigin="anonymous"> </audio>
<div id="visualisation" class="hideIfNoApi"> </div>
</div>
<div id="visualizer_wrapper">
<canvas id='canvas' width="702" height="350" style="border: 1px #eee solid;"></canvas>
</div>
<script>
$(function () {
context = new (window.AudioContext || window.webkitAudioContext)();
// Create the analyser
var analyser = context.createAnalyser();
// https://developer.mozilla.org/zh-TW/docs/Web/API/AnalyserNode/fftSize
analyser.fftSize = 64;
// Get the frequency data and update the visualisation
function update() {
var canvas = document.getElementById('canvas'),
cwidth = canvas.width,
cheight = canvas.height - 2,
meterWidth = 20, //width of the meters in the spectrum
gap = 2, //gap between meters
capHeight = 2,
capStyle = '#fff',
meterNum = 702 / (10 + 2), //count of the meters
capYPositionArray = []; //store the vertical position of hte caps for the preivous frame
ctx = canvas.getContext('2d');
gradient = ctx.createLinearGradient(0, 0, 0, 300);
gradient.addColorStop(1, '#0f0');
gradient.addColorStop(0.5, '#ff0');
gradient.addColorStop(0, '#f00');
var drawMeter = function() {
var array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
ctx.clearRect(0, 0, cwidth, cheight);
for (var i = 0; i < array.length; i++) {
var value = array[i];
if (capYPositionArray.length < Math.round(meterNum)) {
capYPositionArray.push(value);
}
ctx.fillStyle = gradient; //set the filllStyle to gradient for a better look
ctx.fillRect(i * 22 /*频谱条的宽度+条间间距*/ , cheight - value + capHeight, meterWidth, cheight);
}
requestAnimationFrame(drawMeter);
};
requestAnimationFrame(drawMeter);
}
// Hook up the audio routing...
// player -> analyser -> speakers
// (Do this after the player is ready to play - https://code.google.com/p/chromium/issues/detail?id=112368#c4)
$("#player").bind('canplay', function() {
var source = context.createMediaElementSource(this);
source.connect(analyser);
analyser.connect(context.destination);
update();
});
});
</script>
</body>
</html>