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

preview.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. var d3 = require("d3"),
  2. audio = require("./audio.js"),
  3. video = require("./video.js"),
  4. minimap = require("./minimap.js"),
  5. sampleWave = require("./sample-wave.js"),
  6. getRenderer = require("../renderer/"),
  7. getWaveform = require("./waveform.js");
  8. var context = d3.select("canvas").node().getContext("2d");
  9. var theme,
  10. caption,
  11. file,
  12. selection;
  13. function _file(_) {
  14. return arguments.length ? (file = _) : file;
  15. }
  16. function _theme(_) {
  17. return arguments.length ? (theme = _, redraw()) : theme;
  18. }
  19. function _caption(_) {
  20. return arguments.length ? (caption = _, redraw()) : caption;
  21. }
  22. function _selection(_) {
  23. return arguments.length ? (selection = _) : selection;
  24. }
  25. minimap.onBrush(function(extent){
  26. var duration = audio.duration();
  27. selection = {
  28. duration: duration * (extent[1] - extent[0]),
  29. start: extent[0] ? extent[0] * duration : null,
  30. end: extent[1] < 1 ? extent[1] * duration : null
  31. };
  32. d3.select("#duration strong").text(Math.round(10 * selection.duration) / 10)
  33. .classed("red", theme && theme.maxDuration && theme.maxDuration < selection.duration);
  34. });
  35. // Resize video and preview canvas to maintain aspect ratio
  36. function resize(width, height) {
  37. var widthFactor = 640 / width,
  38. heightFactor = 360 / height,
  39. factor = Math.min(widthFactor, heightFactor);
  40. d3.select("canvas")
  41. .attr("width", factor * width)
  42. .attr("height", factor * height);
  43. d3.select("#canvas")
  44. .style("width", (factor * width) + "px");
  45. d3.select("video")
  46. .attr("height", widthFactor * height);
  47. d3.select("#video")
  48. .attr("height", (widthFactor * height) + "px");
  49. context.setTransform(factor, 0, 0, factor, 0, 0);
  50. }
  51. function redraw() {
  52. resize(theme.width, theme.height);
  53. video.kill();
  54. var renderer = getRenderer(theme);
  55. renderer.backgroundImage(theme.backgroundImageFile || null);
  56. renderer.drawFrame(context, {
  57. caption: caption,
  58. waveform: sampleWave,
  59. frame: 0
  60. });
  61. }
  62. function loadAudio(f, cb) {
  63. d3.queue()
  64. .defer(getWaveform, f)
  65. .defer(audio.src, f)
  66. .await(function(err, data){
  67. if (err) {
  68. return cb(err);
  69. }
  70. file = f;
  71. minimap.redraw(data.peaks);
  72. cb(err);
  73. });
  74. }
  75. module.exports = {
  76. caption: _caption,
  77. theme: _theme,
  78. file: _file,
  79. selection: _selection,
  80. loadAudio: loadAudio
  81. };