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

waveform.js 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. var probe = require("../lib/probe.js"),
  2. d3 = require("d3"),
  3. pcmStream = require("../lib/pcm.js");
  4. function getWaveform(filename, options, cb) {
  5. var stream = pcmStream(filename, {
  6. channels: options.channels
  7. }),
  8. samples = [];
  9. stream.on("data",function(sample, channel){
  10. // Average multiple channels
  11. if (channel > 0) {
  12. samples[samples.length - 1] = ((samples[samples.length - 1] * channel) + sample) / (channel + 1);
  13. } else {
  14. samples.push(sample);
  15. }
  16. });
  17. stream.on("error", cb);
  18. stream.on("end", function(output){
  19. var processed = processSamples(samples, options.numFrames, options.samplesPerFrame);
  20. return cb(null, processed);
  21. });
  22. }
  23. function processSamples(samples, numFrames, samplesPerFrame) {
  24. // TODO spread out slop across frames
  25. var perFrame = Math.floor(samples.length / numFrames),
  26. perPoint = Math.floor(perFrame / samplesPerFrame),
  27. range = d3.range(samplesPerFrame),
  28. maxFrame,
  29. min = max = 0;
  30. var unadjusted = d3.range(numFrames).map(function(frame){
  31. var frameSamples = samples.slice(frame * perFrame, (frame + 1) * perFrame);
  32. return range.map(function(point){
  33. var pointSamples = frameSamples.slice(point * perPoint, (point + 1) * perPoint),
  34. localMin = localMax = 0;
  35. for (var i = 0, l = pointSamples.length; i < l; i++) {
  36. localMin = Math.min(localMin, pointSamples[i]);
  37. localMax = Math.max(localMax, pointSamples[i]);
  38. }
  39. min = Math.min(min, localMin);
  40. if (localMax > max) {
  41. max = localMax;
  42. maxFrame = frame;
  43. }
  44. return [localMin, localMax];
  45. });
  46. });
  47. // Scale up to -1 / 1
  48. var adjustment = 1 / Math.max(Math.abs(min), Math.abs(max));
  49. var adjusted = unadjusted.map(function(frame){
  50. return frame.map(function(point){
  51. return [adjustment * point[0], adjustment * point[1]];
  52. });
  53. });
  54. // Make first and last frame peaky
  55. adjusted[0] = adjusted[numFrames - 1] = adjusted[maxFrame];
  56. return adjusted;
  57. }
  58. module.exports = getWaveform;