Turn audio into a shareable video. forked from nypublicradio/audiogram

draw-frames.js 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. var fs = require("fs"),
  2. path = require("path"),
  3. Canvas = require("canvas"),
  4. queue = require("d3").queue;
  5. function drawFrames(renderer, options, cb) {
  6. var frameQueue = queue(10),
  7. canvases = [];
  8. for (var i = 0; i < 10; i++) {
  9. canvases.push(new Canvas(options.width, options.height));
  10. }
  11. for (var i = 0; i < options.numFrames; i++) {
  12. frameQueue.defer(drawFrame, i);
  13. }
  14. frameQueue.awaitAll(cb);
  15. function drawFrame(frameNumber, frameCallback) {
  16. var canvas = canvases.pop(),
  17. context = canvas.getContext("2d");
  18. renderer.drawFrame(context, {
  19. caption: options.caption,
  20. waveform: options.waveform[frameNumber],
  21. frame: frameNumber
  22. });
  23. canvas.toBuffer(function(err, buf){
  24. if (err) {
  25. return cb(err);
  26. }
  27. fs.writeFile(path.join(options.frameDir, zeropad(frameNumber + 1, 6) + ".png"), buf, function(writeErr) {
  28. if (writeErr) {
  29. return frameCallback(writeErr);
  30. }
  31. if (options.tick) {
  32. options.tick();
  33. }
  34. canvases.push(canvas);
  35. return frameCallback(null);
  36. });
  37. });
  38. }
  39. }
  40. function zeropad(str, len) {
  41. str = str.toString();
  42. while (str.length < len) {
  43. str = "0" + str;
  44. }
  45. return str;
  46. }
  47. module.exports = drawFrames;