JSFiddle - React, Tailwind, and code Playground
by Ehsan Ziya
HTML
<canvas id='canvas' width='500px' height='100px'></canvas>
<div id='slider'></div>
JavaScript
var context = new webkitAudioContext();
//loading the file function
function Loader(source,successcallback){
var that = this;
that.source = source;
that.isLoaded = false;
this.buffer = null;
var request = new XMLHttpRequest();
request.open('GET', source , true);
request.responseType = "arraybuffer";
request.onload = function(){
context.decodeAudioData(request.response, function(e){
that.buffer = e;
that.isLoaded = true;
successcallback();
});
};
request.send();
}
//waveform drawer
function drawBuffer( width, height, context, buffer ) {
var data = buffer.getChannelData( 0 );
var step = Math.ceil( data.length / width );
var amp = height / 2;
context.fillStyle = 'white';
context.fillRect(0,0,width,height);
context.fillStyle = 'black';
for(var i=0; i < width; i++){
var min = 1.0;
var max = -1.0;
for (j=0; j<step; j++) {
var datum = data[(i*step)+j];
if (datum < min)
min = datum;
if (datum > max)
max = datum;
}
context.fillRect(i,(1+min)*amp,1,Math.max(1,(max-min)*amp));
}
}
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var url = 'https://dl.dropboxusercontent.com/u/141488253/ZQNCR.mp3';
var file = new Loader(url,function(){
drawBuffer(canvas.width,canvas.height,ctx,file.buffer);
});