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

index.js 7.0KB

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