Skip to content

Commit

Permalink
upgrade the single page version
Browse files Browse the repository at this point in the history
  • Loading branch information
wayou committed Feb 17, 2014
1 parent 702f99f commit d6132af
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions audio_visualizer_single_page_version.html
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@
this.infoUpdateId = null, //to sotore the setTimeout ID and clear the interval
this.animationId = null,
this.status = 0, //flag for sound is playing 1 or stopped 0
this.forceStop = false
this.forceStop = false,
this.allCapsReachBottom = false
};
Visualizer.prototype = {
ini: function() {
Expand Down Expand Up @@ -179,8 +180,10 @@
audioBufferSouceNode.stop = audioBufferSouceNode.noteOff //in old browsers use noteOn method
};
//stop the previous sound if any
if (this.source !== null) {
if (this.animationId !== null) {
cancelAnimationFrame(this.animationId);
}
if (this.source !== null) {
this.source.stop(0);
}
audioBufferSouceNode.start(0);
Expand Down Expand Up @@ -214,13 +217,24 @@
var drawMeter = function() {
var array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
if (that.status === 0) {
//fix when some sounds end the value still not back to zero
for (var i = array.length - 1; i >= 0; i--) {
array[i] = 0;
};
allCapsReachBottom = true;
for (var i = capYPositionArray.length - 1; i >= 0; i--) {
allCapsReachBottom = allCapsReachBottom && (capYPositionArray[i] === 0);
};
if (allCapsReachBottom) {
cancelAnimationFrame(that.animationId);//since the sound is top and animation finished, stop the requestAnimation to prevent potential memory leak,THIS IS VERY IMPORTANT!
return;
};
};
var step = Math.round(array.length / meterNum); //sample limited data from the total array
ctx.clearRect(0, 0, cwidth, cheight);
for (var i = 0; i < meterNum; i++) {
var value = array[i * step];
if (that.status === 0) {
value = 0; //fix when some sounds end the value still not back to zero
};
if (capYPositionArray.length < Math.round(meterNum)) {
capYPositionArray.push(value);
};
Expand All @@ -235,7 +249,7 @@
ctx.fillStyle = gradient; //set the filllStyle to gradient for a better look
ctx.fillRect(i * 12 /*meterWidth+gap*/ , cheight - value + capHeight, meterWidth, cheight); //the meter
}
this.animationId = requestAnimationFrame(drawMeter);
that.animationId = requestAnimationFrame(drawMeter);
}
this.animationId = requestAnimationFrame(drawMeter);
},
Expand All @@ -246,7 +260,6 @@
return;
};
this.status = 0;
console.log('audio ended');
var text = 'HTML5 Audio API showcase | An Audio Viusalizer';
document.getElementById('fileWrapper').style.opacity = 1;
document.getElementById('info').innerHTML = text;
Expand Down

0 comments on commit d6132af

Please sign in to comment.