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

index.js 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. var d3 = require("d3"),
  2. $ = require("jquery"),
  3. preview = require("./preview.js"),
  4. video = require("./video.js"),
  5. audio = require("./audio.js");
  6. d3.json("/settings/labels.json", function(err, labels){
  7. // Populate labels menu
  8. d3.select("#input-label")
  9. .on("change", updateLabel)
  10. .selectAll("option")
  11. .data(labels.podcasts)
  12. .enter()
  13. .append("option")
  14. .text(function(l){
  15. return l;
  16. });
  17. d3.select("#input-label").each(updateLabel);
  18. }); // end label ingestion
  19. d3.json("/settings/themes.json", function(err, themes){
  20. var errorMessage;
  21. // Themes are missing or invalid
  22. if (err || !d3.keys(themes).filter(function(d){ return d !== "default"; }).length) {
  23. if (err instanceof SyntaxError) {
  24. errorMessage = "Error in settings/themes.json:<br/><code>" + err.toString() + "</code>";
  25. } else if (err instanceof ProgressEvent) {
  26. errorMessage = "Error: no settings/themes.json.";
  27. } else if (err) {
  28. errorMessage = "Error: couldn't load settings/themes.json.";
  29. } else {
  30. errorMessage = "No themes found in settings/themes.json.";
  31. }
  32. d3.select("#loading-bars").remove();
  33. d3.select("#loading-message").html(errorMessage);
  34. if (err) {
  35. throw err;
  36. }
  37. return;
  38. }
  39. for (var key in themes) {
  40. themes[key] = $.extend({}, themes.default, themes[key]);
  41. }
  42. preloadImages(themes);
  43. });
  44. function submitted() {
  45. d3.event.preventDefault();
  46. var theme = preview.theme(),
  47. caption = preview.caption(),
  48. selection = preview.selection(),
  49. file = preview.file();
  50. if (!file) {
  51. d3.select("#row-audio").classed("error", true);
  52. return setClass("error", "No audio file selected.");
  53. }
  54. if (theme.maxDuration && selection.duration > theme.maxDuration) {
  55. return setClass("error", "Your Audiogram must be under " + theme.maxDuration + " seconds.");
  56. }
  57. if (!theme || !theme.width || !theme.height) {
  58. return setClass("error", "No valid theme detected.");
  59. }
  60. video.kill();
  61. audio.pause();
  62. var formData = new FormData();
  63. formData.append("audio", file);
  64. if (selection.start || selection.end) {
  65. formData.append("start", selection.start);
  66. formData.append("end", selection.end);
  67. }
  68. formData.append("theme", JSON.stringify($.extend({}, theme, { backgroundImageFile: null })));
  69. formData.append("caption", caption);
  70. setClass("loading");
  71. d3.select("#loading-message").text("Uploading audio...");
  72. $.ajax({
  73. url: "/submit/",
  74. type: "POST",
  75. data: formData,
  76. contentType: false,
  77. dataType: "json",
  78. cache: false,
  79. processData: false,
  80. success: function(data){
  81. poll(data.id, 0);
  82. },
  83. error: error
  84. });
  85. }
  86. function poll(id) {
  87. setTimeout(function(){
  88. $.ajax({
  89. url: "/status/" + id + "/",
  90. error: error,
  91. dataType: "json",
  92. success: function(result){
  93. if (result && result.status && result.status === "ready" && result.url) {
  94. video.update(result.url, preview.theme().name);
  95. setClass("rendered");
  96. } else if (result.status === "error") {
  97. error(result.error);
  98. } else {
  99. d3.select("#loading-message").text(statusMessage(result));
  100. poll(id);
  101. }
  102. }
  103. });
  104. }, 2500);
  105. }
  106. function error(msg) {
  107. if (msg.responseText) {
  108. msg = msg.responseText;
  109. }
  110. if (typeof msg !== "string") {
  111. msg = JSON.stringify(msg);
  112. }
  113. if (!msg) {
  114. msg = "Unknown error";
  115. }
  116. d3.select("#loading-message").text("Loading...");
  117. setClass("error", msg);
  118. }
  119. // Once images are downloaded, set up listeners
  120. function initialize(err, themesWithImages) {
  121. // Populate themes menu
  122. d3.select("#input-theme")
  123. .on("change", updateTheme)
  124. .selectAll("option")
  125. .data(themesWithImages)
  126. .enter()
  127. .append("option")
  128. .text(function(d){
  129. return d.name;
  130. });
  131. // Get initial theme
  132. d3.select("#input-theme").each(updateTheme);
  133. // Get initial caption (e.g. back button)
  134. d3.select("#input-caption").on("change keyup", updateCaption).each(updateCaption);
  135. // Space bar listener for audio play/pause
  136. d3.select(document).on("keypress", function(){
  137. if (!d3.select("body").classed("rendered") && d3.event.key === " " && !d3.matcher("input, textarea, button, select").call(d3.event.target)) {
  138. audio.toggle();
  139. }
  140. });
  141. // Button listeners
  142. d3.selectAll("#play, #pause").on("click", function(){
  143. d3.event.preventDefault();
  144. audio.toggle();
  145. });
  146. d3.select("#restart").on("click", function(){
  147. d3.event.preventDefault();
  148. audio.restart();
  149. });
  150. // If there's an initial piece of audio (e.g. back button) load it
  151. d3.select("#input-audio").on("change", updateAudioFile).each(updateAudioFile);
  152. d3.select("#return").on("click", function(){
  153. d3.event.preventDefault();
  154. video.kill();
  155. setClass(null);
  156. });
  157. d3.select("#submit").on("click", submitted);
  158. }
  159. function updateAudioFile() {
  160. d3.select("#row-audio").classed("error", false);
  161. audio.pause();
  162. video.kill();
  163. // Skip if empty
  164. if (!this.files || !this.files[0]) {
  165. d3.select("#minimap").classed("hidden", true);
  166. preview.file(null);
  167. setClass(null);
  168. return true;
  169. }
  170. d3.select("#loading-message").text("Analyzing...");
  171. setClass("loading");
  172. preview.loadAudio(this.files[0], function(err){
  173. if (err) {
  174. d3.select("#row-audio").classed("error", true);
  175. setClass("error", "Error decoding audio file");
  176. } else {
  177. setClass(null);
  178. }
  179. d3.selectAll("#minimap, #submit").classed("hidden", !!err);
  180. });
  181. }
  182. function updateCaption() {
  183. preview.caption(this.value);
  184. }
  185. function updateLabel() {
  186. preview.label(this.value);
  187. }
  188. function updateTheme() {
  189. preview.theme(d3.select(this.options[this.selectedIndex]).datum());
  190. }
  191. function preloadImages(themes) {
  192. // preload images
  193. var imageQueue = d3.queue();
  194. d3.entries(themes).forEach(function(theme){
  195. if (!theme.value.name) {
  196. theme.value.name = theme.key;
  197. }
  198. if (theme.key !== "default") {
  199. imageQueue.defer(getImage, theme.value);
  200. }
  201. });
  202. imageQueue.awaitAll(initialize);
  203. function getImage(theme, cb) {
  204. if (!theme.backgroundImage) {
  205. return cb(null, theme);
  206. }
  207. theme.backgroundImageFile = new Image();
  208. theme.backgroundImageFile.onload = function(){
  209. return cb(null, theme);
  210. };
  211. theme.backgroundImageFile.onerror = function(e){
  212. console.warn(e);
  213. return cb(null, theme);
  214. };
  215. theme.backgroundImageFile.src = "/settings/backgrounds/" + theme.backgroundImage;
  216. }
  217. }
  218. function setClass(cl, msg) {
  219. d3.select("body").attr("class", cl || null);
  220. d3.select("#error").text(msg || "");
  221. }
  222. function statusMessage(result) {
  223. switch (result.status) {
  224. case "queued":
  225. return "Waiting for other jobs to finish, #" + (result.position + 1) + " in queue";
  226. case "audio-download":
  227. return "Downloading audio for processing";
  228. case "trim":
  229. return "Trimming audio";
  230. case "probing":
  231. return "Probing audio file";
  232. case "waveform":
  233. return "Analyzing waveform";
  234. case "renderer":
  235. return "Initializing renderer";
  236. case "frames":
  237. var msg = "Generating frames";
  238. if (result.numFrames) {
  239. msg += ", " + Math.round(100 * (result.framesComplete || 0) / result.numFrames) + "% complete";
  240. }
  241. return msg;
  242. case "combine":
  243. return "Combining frames with audio";
  244. case "ready":
  245. return "Cleaning up";
  246. default:
  247. return JSON.stringify(result);
  248. }
  249. }