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

index.js 7.4KB

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