Last active
October 9, 2015 05:28
-
-
Save kn0ll/3445507 to your computer and use it in GitHub Desktop.
a backbone view for creating a waveform png from an audio buffer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var BufferDrawer = Backbone.View.extend({ | |
initialize: function(options) { | |
this.buffer = options.buffer; | |
return Backbone.Model.prototype.initialize.apply(this, arguments); | |
}, | |
draw: function() { | |
var channels = this.buffer.channels, | |
channel = _(channels).last(), | |
samples = _.flatten(channel), | |
normalized_samples = []; | |
var height = 255, | |
width = 5000, | |
png = new PNGlib(width, height, 256), | |
background = png.color(0, 0, 0, 0), | |
samples_per_px = Math.floor(samples.length / width); | |
_(samples).each(function(sample, i) { | |
if (!(i % samples_per_px)) { | |
var scaledValue = 128.0 * (sample + 1.0); | |
normalized_samples.push(scaledValue); | |
} | |
}); | |
_(normalized_samples).each(function(sample, i) { | |
var normalized_y = Math.floor(height - sample); | |
png.buffer[png.index(i, normalized_y)] = png.color(0xcc, 0x00, 0x44); | |
}); | |
return png; | |
}, | |
render: function() { | |
var png = this.draw(); | |
this.setElement($('<img src="data:image/png;base64,'+ png.getBase64() + '" />')); | |
return this; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment