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

index.js 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var d3 = require("d3"),
  2. patterns = require("./patterns.js"),
  3. sample = require("./sample-wave.js"),
  4. textWrapper = require("./text-wrapper.js");
  5. module.exports = function(context) {
  6. context.patternQuality = "best";
  7. var renderer = {};
  8. renderer.context = context;
  9. renderer.update = function(options) {
  10. options.backgroundColor = options.backgroundColor || "#fff";
  11. options.waveColor = options.waveColor || options.foregroundColor || "#000";
  12. options.captionColor = options.captionColor || options.foregroundColor || "#000";
  13. if (typeof options.waveTop !== "number") {
  14. options.waveTop = 0;
  15. }
  16. if (typeof options.waveBottom !== "number") {
  17. options.waveBottom = options.height;
  18. }
  19. this.wrapText = textWrapper(context, options);
  20. this.options = options;
  21. this.waveform = options.waveform || [sample.slice(0, options.samplesPerFrame)];
  22. return this;
  23. };
  24. // Get the waveform data for this frame
  25. renderer.getWaveform = function(frameNumber) {
  26. return this.waveform[Math.min(this.waveform.length - 1, frameNumber)];
  27. };
  28. // Draw the frame
  29. renderer.drawFrame = function(frameNumber) {
  30. // Draw the background image and/or background color
  31. context.clearRect(0, 0, this.options.width, this.options.height);
  32. context.fillStyle = this.options.backgroundColor;
  33. context.fillRect(0, 0, this.options.width, this.options.height);
  34. if (this.backgroundImage) {
  35. context.drawImage(this.backgroundImage, 0, 0, this.options.width, this.options.height);
  36. }
  37. patterns[this.options.pattern || "wave"](context, this.getWaveform(frameNumber), this.options);
  38. // Write the caption
  39. if (this.caption) {
  40. this.wrapText(this.caption);
  41. }
  42. return this;
  43. };
  44. return renderer;
  45. }