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

minimap.js 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. var d3 = require("d3");
  2. var minimap = d3.select("#minimap"),
  3. svg = minimap.select("svg"),
  4. onBrush = onBrushEnd = function(){};
  5. var t = d3.scaleLinear()
  6. .domain([0, 640])
  7. .range([0,1])
  8. .clamp(true);
  9. var y = d3.scaleLinear()
  10. .domain([0, 1])
  11. .range([40, 0]);
  12. var line = d3.line();
  13. var brush = d3.brushX()
  14. .on("brush end", brushed)
  15. minimap.select(".brush").call(brush)
  16. .selectAll("rect")
  17. .attr("height", 80);
  18. minimap.selectAll(".brush .resize")
  19. .append("line")
  20. .attr("x1",0)
  21. .attr("x2",0)
  22. .attr("y1",0)
  23. .attr("y2", 80);
  24. function redraw(data) {
  25. brush.move(d3.select(".brush"), [0, 0]);
  26. var top = data.map(function(d,i){
  27. return [i, y(d)];
  28. });
  29. var bottom = top.map(function(d){
  30. return [d[0], 80 - d[1]];
  31. }).reverse();
  32. d3.selectAll("g.waveform path")
  33. .attr("d",line(top.concat(bottom)));
  34. time(0);
  35. }
  36. function time(t) {
  37. d3.select("g.time")
  38. .attr("transform","translate(" + (t * 640) + ")");
  39. }
  40. function brushed() {
  41. var start = d3.event.selection ? t(d3.event.selection[0]) : 0,
  42. end = d3.event.selection ? t(d3.event.selection[1]) : 1;
  43. if (start === end) {
  44. start = 0;
  45. end = 1;
  46. } else {
  47. if (start <= 0.01) {
  48. start = 0;
  49. }
  50. if (end >= 0.99) {
  51. end = 1;
  52. }
  53. }
  54. d3.select("clipPath rect")
  55. .attr("x", t.invert(start))
  56. .attr("width", t.invert(end - start));
  57. onBrush([start, end]);
  58. if (d3.event.type === "end") {
  59. onBrushEnd([start, end]);
  60. }
  61. }
  62. function _onBrush(_) {
  63. onBrush = _;
  64. }
  65. function _onBrushEnd(_) {
  66. onBrushEnd = _;
  67. }
  68. module.exports = {
  69. time: time,
  70. redraw: redraw,
  71. onBrush: _onBrush,
  72. onBrushEnd: _onBrushEnd
  73. };