Skip to content

Instantly share code, notes, and snippets.

@danigb
Last active October 16, 2020 20:57
Show Gist options
  • Save danigb/ffe0c4e7a06586d4bbb018ca69887ae8 to your computer and use it in GitHub Desktop.
Save danigb/ffe0c4e7a06586d4bbb018ca69887ae8 to your computer and use it in GitHub Desktop.
Draw a waveform data to canvas (partially based on https://github.com/cwilso/Audio-Buffer-Draw by the great @cwilso)
module.exports = function (canvas, data, color, maxStep = 1000) {
var ctx = canvas.getContext('2d')
if (color) ctx.fillStyle = color
var width = canvas.width
var height = canvas.height
var step = Math.ceil(data.length / width)
var amp = height / 2
for (var i = 0; i < width; i++) {
var neg = 0
var pos = 0
var max = Math.min(step, maxStep)
for (var j = 0; j < max; j++) {
var val = data[(i * step) + j]
if (val < 0) neg += val
else pos += val
}
neg = neg / max
pos = pos / max
ctx.fillRect(i, amp - pos * amp, 1, amp * (pos - neg))
}
}
{
"name": "draw-waveform",
"main": "draw-waveform.js",
"version": "1.0.0"
}

Install it via npm: npm i --save gist:ffe0c4e7a06586d4bbb018ca69887ae8

And then:

var draw = require('draw-waveform')
// given a canvas and an audio buffer...
draw(canvas, buffer.getChannelData(0), 'blue')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment