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

audio.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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.duration) {
  31. var pos = audio.currentTime / audio.duration;
  32. // Need some allowance at the beginning because of frame imprecision (esp. FF)
  33. if (audio.ended || pos >= extent[1] || audio.duration * extent[0] - audio.currentTime > 0.2) {
  34. pause(extent[0] * audio.duration);
  35. }
  36. minimap.time(pos);
  37. }
  38. }
  39. function toggled(paused) {
  40. d3.select("#pause").classed("hidden", paused);
  41. d3.select("#play").classed("hidden", !paused);
  42. }
  43. function toggle() {
  44. if (isPlaying()) {
  45. pause();
  46. } else {
  47. play();
  48. }
  49. }
  50. function _extent(_) {
  51. if (arguments.length) {
  52. extent = _;
  53. var pos = audio.currentTime / audio.duration;
  54. if (pos > extent[1] || audio.duration * extent[0] - audio.currentTime > 0.2 || !isPlaying()) {
  55. pause(extent[0] * audio.duration);
  56. }
  57. minimap.time(pos);
  58. } else {
  59. return extent;
  60. }
  61. }
  62. function src(file, cb) {
  63. d3.select("audio")
  64. .on("canplaythrough", cb)
  65. .on("error", function(){
  66. cb(d3.event.target.error);
  67. })
  68. .select("source")
  69. .attr("type", file.type)
  70. .attr("src", URL.createObjectURL(file));
  71. audio.load();
  72. }
  73. function isPlaying() {
  74. return audio.duration && !audio.paused && !audio.ended && 0 < audio.currentTime;
  75. }
  76. function _duration() {
  77. return audio.duration;
  78. }
  79. module.exports = {
  80. play: play,
  81. pause: pause,
  82. toggle: toggle,
  83. src: src,
  84. restart: restart,
  85. duration: _duration
  86. };