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

draw-frames.js 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. var fs = require("fs"),
  2. path = require("path"),
  3. Canvas = require("../vendor/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. citation: options.citation,
  21. label: options.label,
  22. waveform: options.waveform[frameNumber],
  23. frame: frameNumber
  24. });
  25. canvas.toBuffer(function(err, buf) {
  26. if (err) {
  27. return cb(err);
  28. }
  29. fs.writeFile(
  30. path.join(options.frameDir, zeropad(frameNumber + 1, 6) + ".png"),
  31. buf,
  32. function(writeErr) {
  33. if (writeErr) {
  34. return frameCallback(writeErr);
  35. }
  36. if (options.tick) {
  37. options.tick();
  38. }
  39. canvases.push(canvas);
  40. return frameCallback(null);
  41. }
  42. );
  43. });
  44. }
  45. }
  46. function zeropad(str, len) {
  47. str = str.toString();
  48. while (str.length < len) {
  49. str = "0" + str;
  50. }
  51. return str;
  52. }
  53. module.exports = drawFrames;