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

audio.js 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. var minimap = require("./minimap.js"),
  2. d3 = require("d3");
  3. var audio = document.querySelector("audio"),
  4. extent = [0, 1];
  5. // timeupdate is too low-res
  6. d3.timer(update);
  7. d3.select(audio).on("play", toggled)
  8. .on("pause", function(){ toggled(true); });
  9. minimap.onBrushEnd(_extent);
  10. function pause(time) {
  11. if (arguments.length) {
  12. audio.currentTime = time;
  13. }
  14. if (isPlaying()) {
  15. audio.pause();
  16. }
  17. toggled(true);
  18. }
  19. function play(time) {
  20. if (arguments.length) {
  21. audio.currentTime = time;
  22. }
  23. audio.play();
  24. toggled();
  25. }
  26. function restart() {
  27. play(extent[0] * audio.duration);
  28. }
  29. function update() {
  30. if (!audio) {
  31. return;
  32. }
  33. if (audio.duration) {
  34. var pos = audio.currentTime / audio.duration;
  35. // Need some allowance at the beginning because of frame imprecision (esp. FF)
  36. if (audio.ended || pos >= extent[1] || audio.duration * extent[0] - audio.currentTime > 0.2) {
  37. pause(extent[0] * audio.duration);
  38. }
  39. minimap.time(pos);
  40. }
  41. }
  42. function toggled(paused) {
  43. d3.select("#pause").classed("hidden", paused);
  44. d3.select("#play").classed("hidden", !paused);
  45. }
  46. function toggle() {
  47. if (isPlaying()) {
  48. pause();
  49. } else {
  50. play();
  51. }
  52. }
  53. function _extent(_) {
  54. if (arguments.length) {
  55. extent = _;
  56. var pos = audio.currentTime / audio.duration;
  57. if (pos > extent[1] || audio.duration * extent[0] - audio.currentTime > 0.2 || !isPlaying()) {
  58. pause(extent[0] * audio.duration);
  59. }
  60. minimap.time(pos);
  61. } else {
  62. return extent;
  63. }
  64. }
  65. function src(file, cb) {
  66. d3.select("audio")
  67. .on("canplaythrough", cb)
  68. .on("error", function(){
  69. cb(d3.event.target.error);
  70. })
  71. .select("source")
  72. .attr("type", file.type)
  73. .attr("src", URL.createObjectURL(file));
  74. audio.load();
  75. }
  76. function isPlaying() {
  77. return audio.duration && !audio.paused && !audio.ended && 0 < audio.currentTime;
  78. }
  79. function _duration() {
  80. return audio.duration;
  81. }
  82. module.exports = {
  83. play: play,
  84. pause: pause,
  85. toggle: toggle,
  86. src: src,
  87. restart: restart,
  88. duration: _duration
  89. };