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

index.js 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. this.wrapText = textWrapper(context, options);
  14. this.options = options;
  15. this.waveform = options.waveform || [sample.slice(0, options.samplesPerFrame)];
  16. return this;
  17. };
  18. // Get the waveform data for this frame
  19. renderer.getWaveform = function(frameNumber) {
  20. return this.waveform[Math.min(this.waveform.length - 1, frameNumber)];
  21. };
  22. // Draw the frame
  23. renderer.drawFrame = function(frameNumber) {
  24. // Draw the background image and/or background color
  25. context.clearRect(0, 0, this.options.width, this.options.height);
  26. context.fillStyle = this.options.backgroundColor;
  27. context.fillRect(0, 0, this.options.width, this.options.height);
  28. if (this.backgroundImage) {
  29. context.drawImage(this.backgroundImage, 0, 0, this.options.width, this.options.height);
  30. }
  31. patterns[this.options.pattern || "wave"](context, this.getWaveform(frameNumber), this.options);
  32. // Write the caption
  33. if (this.caption) {
  34. this.wrapText(this.caption);
  35. }
  36. return this;
  37. };
  38. return renderer;
  39. }