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

index.js 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. var d3 = require("d3"),
  2. $ = require("jquery"),
  3. preview = require("./preview.js"),
  4. video = require("./video.js"),
  5. audio = require("./audio.js"),
  6. themeEditor = require("./themeEditor.js");
  7. d3.json("/settings/themes.json", function(err, themes){
  8. var errorMessage;
  9. // Themes are missing or invalid
  10. if (err || !d3.keys(themes).filter(function(d){ return d !== "default"; }).length) {
  11. if (err instanceof SyntaxError) {
  12. errorMessage = "Error in settings/themes.json:<br/><code>" + err.toString() + "</code>";
  13. } else if (err instanceof ProgressEvent) {
  14. errorMessage = "Error: no settings/themes.json.";
  15. } else if (err) {
  16. errorMessage = "Error: couldn't load settings/themes.json.";
  17. } else {
  18. errorMessage = "No themes found in settings/themes.json.";
  19. }
  20. d3.select("#loading-bars").remove();
  21. d3.select("#loading-message").html(errorMessage);
  22. if (err) {
  23. throw err;
  24. }
  25. return;
  26. }
  27. if(themeEditor.isEditor())
  28. themeEditor.initializeThemes(themes);
  29. for (var key in themes) {
  30. themes[key] = $.extend({}, themes.default, themes[key]);
  31. }
  32. preloadImages(themes);
  33. });
  34. function submitted() {
  35. d3.event.preventDefault();
  36. var theme = preview.theme(),
  37. caption = preview.caption(),
  38. selection = preview.selection(),
  39. file = preview.file();
  40. if (!file) {
  41. d3.select("#row-audio").classed("error", true);
  42. return setClass("error", "No audio file selected.");
  43. }
  44. if (theme.maxDuration && selection.duration > theme.maxDuration) {
  45. return setClass("error", "Your Audiogram must be under " + theme.maxDuration + " seconds.");
  46. }
  47. if (!theme || !theme.width || !theme.height) {
  48. return setClass("error", "No valid theme detected.");
  49. }
  50. video.kill();
  51. audio.pause();
  52. var formData = new FormData();
  53. formData.append("audio", file);
  54. if (selection.start || selection.end) {
  55. formData.append("start", selection.start);
  56. formData.append("end", selection.end);
  57. }
  58. formData.append("theme", JSON.stringify($.extend({}, theme, { backgroundImageFile: null })));
  59. formData.append("caption", caption);
  60. setClass("loading");
  61. d3.select("#loading-message").text("Uploading audio...");
  62. $.ajax({
  63. url: "/submit/",
  64. type: "POST",
  65. data: formData,
  66. contentType: false,
  67. dataType: "json",
  68. cache: false,
  69. processData: false,
  70. success: function(data){
  71. poll(data.id, 0);
  72. },
  73. error: error
  74. });
  75. }
  76. function poll(id) {
  77. setTimeout(function(){
  78. $.ajax({
  79. url: "/status/" + id + "/",
  80. error: error,
  81. dataType: "json",
  82. success: function(result){
  83. if (result && result.status && result.status === "ready" && result.url) {
  84. video.update(result.url, preview.theme().name);
  85. setClass("rendered");
  86. } else if (result.status === "error") {
  87. error(result.error);
  88. } else {
  89. d3.select("#loading-message").text(statusMessage(result));
  90. poll(id);
  91. }
  92. }
  93. });
  94. }, 2500);
  95. }
  96. function error(msg) {
  97. if (msg.responseText) {
  98. msg = msg.responseText;
  99. }
  100. if (typeof msg !== "string") {
  101. msg = JSON.stringify(msg);
  102. }
  103. if (!msg) {
  104. msg = "Unknown error";
  105. }
  106. d3.select("#loading-message").text("Loading...");
  107. setClass("error", msg);
  108. }
  109. // Once images are downloaded, set up listeners
  110. function initialize(err, themesWithImages) {
  111. // Populate dropdown menu
  112. d3.select("#input-theme")
  113. .on("change.a", updateTheme)
  114. .on("change.b", function(){
  115. if(themeEditor.isActive())
  116. themeEditor.populateThemeFields();
  117. })
  118. .selectAll("option")
  119. .data(themesWithImages)
  120. .enter()
  121. .append("option")
  122. .text(function(d){
  123. return d.name;
  124. });
  125. // Get initial theme
  126. d3.select("#input-theme").each(updateTheme);
  127. // Get initial caption (e.g. back button)
  128. d3.select("#input-caption").on("change keyup", updateCaption).each(updateCaption);
  129. // Space bar listener for audio play/pause
  130. d3.select(document).on("keypress", function(){
  131. if (!d3.select("body").classed("rendered") && d3.event.key === " " && !d3.matcher("input, textarea, button, select").call(d3.event.target)) {
  132. audio.toggle();
  133. }
  134. });
  135. // Button listeners
  136. d3.selectAll("#play, #pause").on("click", function(){
  137. d3.event.preventDefault();
  138. audio.toggle();
  139. });
  140. d3.select("#restart").on("click", function(){
  141. d3.event.preventDefault();
  142. audio.restart();
  143. });
  144. // If there's an initial piece of audio (e.g. back button) load it
  145. d3.select("#input-audio").on("change", updateAudioFile).each(updateAudioFile);
  146. d3.select("#return").on("click", function(){
  147. d3.event.preventDefault();
  148. video.kill();
  149. setClass(null);
  150. });
  151. d3.select("#submit").on("click", submitted);
  152. d3.select("#theme-edit").on("click", function(){
  153. var activeTheme = d3.select('#input-theme').property('value');
  154. var url = window.location.origin + window.location.pathname + 'themes.html?t=' + activeTheme;
  155. window.location = url;
  156. });
  157. d3.select("#new-theme").on("click", function(){
  158. var url = window.location.origin + window.location.pathname + 'themes.html?t=default'
  159. window.location = url;
  160. });
  161. if(themeEditor.isEditor())
  162. themeEditor.initialize();
  163. }
  164. function updateAudioFile() {
  165. d3.select("#row-audio").classed("error", false);
  166. audio.pause();
  167. video.kill();
  168. // Skip if empty
  169. if (!this.files || !this.files[0]) {
  170. d3.select("#minimap").classed("hidden", true);
  171. preview.file(null);
  172. setClass(null);
  173. return true;
  174. }
  175. d3.select("#loading-message").text("Analyzing...");
  176. setClass("loading");
  177. preview.loadAudio(this.files[0], function(err){
  178. if (err) {
  179. d3.select("#row-audio").classed("error", true);
  180. setClass("error", "Error decoding audio file");
  181. } else {
  182. setClass(null);
  183. }
  184. d3.selectAll("#minimap, #submit").classed("hidden", !!err);
  185. });
  186. }
  187. function updateCaption() {
  188. preview.caption(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. }