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

index.js 6.9KB

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