JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<canvas id="canvas"></canvas>
<input id="fileItem" type="file"/>
<button id="button" onclick="initAudio();">Draw Waveform</button>
</body>
CSS
body {
width: 100%;
height: 100%;
}
#canvas {
position: absolute;
top: 0;
left; 0;
width: 800px;
height: 200px;
background-color: blue;
}
#fileItem {
position: absolute;
top: 205px;
left: 0px;
}
#button {
position: absolute;
top: 205px;
left: 250px;
JavaScript
var audioContext = new AudioContext();
function drawBuffer( width, height, context, buffer ) {
var data = buffer.getChannelData( 0 );
var step = Math.ceil( data.length / width );
var amp = height / 2;
for(var i=0; i < width; i++){
var min = 1.0;
var max = -1.0;
for (var 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));
}
}
function initAudio() {
var file = document.getElementById('fileItem').files[0];
var reader = new FileReader();
reader.onerror = function(e) {
console.log("Error reading file");
console.log(e);
}
reader.onload = function(e) {
console.log("loading");
var arrayBuffer = e.target.result;
audioContext.decodeAudioData( arrayBuffer,
function(buffer) {
console.log("drawing");
var canvas = document.getElementById("canvas");
drawBuffer( canvas.width, canvas.height, canvas.getContext('2d'), buffer );
} );
}
reader.readAsArrayBuffer(file);
}