Skip to content

Instantly share code, notes, and snippets.

@kn0ll
Last active October 9, 2015 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kn0ll/3445507 to your computer and use it in GitHub Desktop.
Save kn0ll/3445507 to your computer and use it in GitHub Desktop.
a backbone view for creating a waveform png from an audio buffer.
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