Use AudioContext to Analysis of the Audio data to synchronize the canvas
#1 Include the JS in HTML #2 Give a box for the MusicCanvas, like this:
<input type="file" id="ff" accept="audio/mpeg">
<section id="myAcBox" style="margin-left: 200px">
</section>
#3 Then write your JS to init the MusicCanvas, First Parameter is input tag id, Necessary. Second Parameter is a object for the options, It's not necessary. like this:
var options={
needPreNext:true, //enable the buffer list
//set canvas size
size:{
width: 720,
height: 405,
}
}
var MC = new initMusicCanvas().init('myAcBox',options);
//Load Music by Select local file
var musicCanvas = MC.bySelectFile('ff');
//load Music by ArrayBuffer
var musicCanvas = MC.bySelectFile(ArrayBuffer);
musicCanvas.audioApi.addEventListener('loading',function () {
//when decoding the mp3 or ArrayBuffer
});
musicCanvas.audioApi.addEventListener('playing',function () {
//when playing
});
musicCanvas.audioApi.addEventListener('ended',function () {
//when music ended
});
The callback provide a Parameter of Array, the Array has the realtime audio frequency data ,and you can use these data to painting
var musicCanvas = new initMusicCanvas().init('myAcBox',{needPreNext:true}).bySelectFile('ff');
var canvas = musicCanvas.canvas;
var ctx = musicCanvas.ctx;
musicCanvas.drawing.addEventListener('onDrawing',function (dataArray) {
var cwidth = canvas.width,cheight = canvas.height;
var mid=0,head=0;
var len = dataArray.length
for(var j=600;j<len;j++){
mid=mid+dataArray[j]
}
for(var k=0;k<20;k++){
head=head+dataArray[k]
}
ctx.beginPath();
ctx.fillStyle='#fee';
ctx.arc(cwidth/4,cheight/2,head/20*size,0,Math.PI*2);
ctx.arc(cwidth/2,cheight/2,mid/623*size*3,0,Math.PI*2);
ctx.closePath();
ctx.fill();
})