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

index.js 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. if (theme.labelText) {
  62. label = theme.labelText;
  63. }
  64. video.kill();
  65. audio.pause();
  66. var formData = new FormData();
  67. formData.append("audio", file);
  68. if (selection.start || selection.end) {
  69. formData.append("start", selection.start);
  70. formData.append("end", selection.end);
  71. }
  72. formData.append("theme", JSON.stringify($.extend({}, theme, { backgroundImageFile: null })));
  73. formData.append("caption", caption);
  74. formData.append("label", label);
  75. setClass("loading");
  76. d3.select("#loading-message").text("Uploading audio...");
  77. $.ajax({
  78. url: "/submit/",
  79. type: "POST",
  80. data: formData,
  81. contentType: false,
  82. dataType: "json",
  83. cache: false,
  84. processData: false,
  85. success: function(data){
  86. poll(data.id, 0);
  87. },
  88. error: error
  89. });
  90. }
  91. function poll(id) {
  92. setTimeout(function(){
  93. $.ajax({
  94. url: "/status/" + id + "/",
  95. error: error,
  96. dataType: "json",
  97. success: function(result){
  98. if (result && result.status && result.status === "ready" && result.url) {
  99. video.update(result.url, preview.theme().name);
  100. setClass("rendered");
  101. } else if (result.status === "error") {
  102. error(result.error);
  103. } else {
  104. d3.select("#loading-message").text(statusMessage(result));
  105. poll(id);
  106. }
  107. }
  108. });
  109. }, 2500);
  110. }
  111. function error(msg) {
  112. if (msg.responseText) {
  113. msg = msg.responseText;
  114. }
  115. if (typeof msg !== "string") {
  116. msg = JSON.stringify(msg);
  117. }
  118. if (!msg) {
  119. msg = "Unknown error";
  120. }
  121. d3.select("#loading-message").text("Loading...");
  122. setClass("error", msg);
  123. }
  124. // Once images are downloaded, set up listeners
  125. function initialize(err, themesWithImages) {
  126. // Populate themes menu
  127. d3.select("#input-theme")
  128. .on("change", updateTheme)
  129. .selectAll("option")
  130. .data(themesWithImages)
  131. .enter()
  132. .append("option")
  133. .text(function(d){
  134. return d.name;
  135. });
  136. // Get initial theme
  137. d3.select("#input-theme").each(updateTheme);
  138. // Get initial caption (e.g. back button)
  139. d3.select("#input-caption").on("change keyup", updateCaption).each(updateCaption);
  140. // Space bar listener for audio play/pause
  141. d3.select(document).on("keypress", function(){
  142. if (!d3.select("body").classed("rendered") && d3.event.key === " " && !d3.matcher("input, textarea, button, select").call(d3.event.target)) {
  143. audio.toggle();
  144. }
  145. });
  146. // Button listeners
  147. d3.selectAll("#play, #pause").on("click", function(){
  148. d3.event.preventDefault();
  149. audio.toggle();
  150. });
  151. d3.select("#restart").on("click", function(){
  152. d3.event.preventDefault();
  153. audio.restart();
  154. });
  155. // If there's an initial piece of audio (e.g. back button) load it
  156. d3.select("#input-audio").on("change", updateAudioFile).each(updateAudioFile);
  157. d3.select("#return").on("click", function(){
  158. d3.event.preventDefault();
  159. video.kill();
  160. setClass(null);
  161. });
  162. d3.select("#submit").on("click", submitted);
  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 updateLabel() {
  191. preview.label(this.value);
  192. }
  193. function updateTheme() {
  194. var theme_obj = d3.select(this.options[this.selectedIndex]).datum(),
  195. that = this;
  196. // Automatically set the label for themes that have them
  197. preview.theme(theme_obj);
  198. if (theme_obj.labelText) {
  199. preview.label(theme_obj.labelText);
  200. $('#input-label').children().each(function (i, c) {
  201. if (c.value === that.options[that.selectedIndex].value) {
  202. $(c).prop('selected', true);
  203. return false;
  204. }
  205. });
  206. $('#input-label').prop('disabled', true);
  207. }
  208. else {
  209. $('#input-label').prop('disabled', false);
  210. }
  211. }
  212. function preloadImages(themes) {
  213. // preload images
  214. var imageQueue = d3.queue();
  215. d3.entries(themes).forEach(function(theme){
  216. if (!theme.value.name) {
  217. theme.value.name = theme.key;
  218. }
  219. if (theme.key !== "default") {
  220. imageQueue.defer(getImage, theme.value);
  221. }
  222. });
  223. imageQueue.awaitAll(initialize);
  224. function getImage(theme, cb) {
  225. if (!theme.backgroundImage) {
  226. return cb(null, theme);
  227. }
  228. theme.backgroundImageFile = new Image();
  229. theme.backgroundImageFile.onload = function(){
  230. return cb(null, theme);
  231. };
  232. theme.backgroundImageFile.onerror = function(e){
  233. console.warn(e);
  234. return cb(null, theme);
  235. };
  236. theme.backgroundImageFile.src = "/settings/backgrounds/" + theme.backgroundImage;
  237. }
  238. }
  239. function setClass(cl, msg) {
  240. d3.select("body").attr("class", cl || null);
  241. d3.select("#error").text(msg || "");
  242. }
  243. function statusMessage(result) {
  244. switch (result.status) {
  245. case "queued":
  246. return "Waiting for other jobs to finish, #" + (result.position + 1) + " in queue";
  247. case "audio-download":
  248. return "Downloading audio for processing";
  249. case "trim":
  250. return "Trimming audio";
  251. case "probing":
  252. return "Probing audio file";
  253. case "waveform":
  254. return "Analyzing waveform";
  255. case "renderer":
  256. return "Initializing renderer";
  257. case "frames":
  258. var msg = "Generating frames";
  259. if (result.numFrames) {
  260. msg += ", " + Math.round(100 * (result.framesComplete || 0) / result.numFrames) + "% complete";
  261. }
  262. return msg;
  263. case "combine":
  264. return "Combining frames with audio";
  265. case "ready":
  266. return "Cleaning up";
  267. default:
  268. return JSON.stringify(result);
  269. }
  270. }