Skip to content

Use AudioContext to Analysis of the Audio data to synchronize the canvas

Notifications You must be signed in to change notification settings

lkkchen/MusicCanvas

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MusicCanvas

Use AudioContext to Analysis of the Audio data to synchronize the canvas

Image text

How to Use

#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);

The musicCanvas has some attributes:

musicCanvas.ctx

the context of canvas,use it to draw

musicCanvas.canvas

the element of canvas

musicCanvas.audioApi

audioApi has some Events:

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
});

musicCanvas.drawing

It's has a Event: onDrawing, All you drawing will write in this Event Callback Function

The callback provide a Parameter of Array, the Array has the realtime audio frequency data ,and you can use these data to painting

Like this:

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();
})

Image text

More Functions Coming Soon~

Some Problems:

Ajax file too slowly, use the stream data will be better

I want to make the drawing is complete control by users, or they can painting by mouse, Not the code we has write done

About

Use AudioContext to Analysis of the Audio data to synchronize the canvas

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published