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

waveform.js 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var extractPeaks = require("webaudio-peaks"),
  2. d3 = require("d3");
  3. var width = 640;
  4. function decoded(cb) {
  5. return function(decodedData) {
  6. var duration = decodedData.duration;
  7. var samplesPerPixel = Math.floor(decodedData.length / width);
  8. var peaks = extractPeaks(decodedData, samplesPerPixel, true);
  9. // FF and Chrome support Int8Array.filter, Safari doesn't, that's fun
  10. var positive = Array.prototype.filter.call(peaks.data[0], function(d,i){
  11. return i % 2;
  12. });
  13. var scale = d3.scaleLinear()
  14. .domain([0, getMax(positive)])
  15. .range([0, 1])
  16. .clamp(true);
  17. positive = Array.prototype.slice.call(positive).map(scale);
  18. cb(null,{ duration: duration, peaks: positive });
  19. };
  20. }
  21. module.exports = function(file, cb) {
  22. var ctx = new (window.AudioContext || window.webkitAudioContext)();
  23. var fileReader = new FileReader();
  24. var close = function(err, data) {
  25. ctx.close();
  26. cb(err, data);
  27. };
  28. fileReader.onerror = cb;
  29. fileReader.onload = function(){
  30. ctx.decodeAudioData(this.result, decoded(close), function(err){ close(err || "Error decoding audio."); });
  31. };
  32. fileReader.readAsArrayBuffer(file);
  33. }
  34. // Faster
  35. function getMax(arr) {
  36. var max = -Infinity;
  37. for (var i = 0, l = arr.length; i < l; i++) {
  38. if (arr[i] > max) {
  39. max = arr[i];
  40. }
  41. }
  42. return max;
  43. }