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

waveform.js 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. maxRms = maxMid = 0;
  30. var unadjusted = d3.range(numFrames).map(function(frame){
  31. var frameSamples = samples.slice(frame * perFrame, (frame + 1) * perFrame),
  32. points = range.map(function(point){
  33. var pointSamples = frameSamples.slice(point * perPoint, (point + 1) * perPoint),
  34. midpoint = pointSamples[Math.floor(pointSamples.length / 2)];
  35. var rms = Math.sqrt(d3.sum(pointSamples.map(function(d){
  36. return d * d;
  37. })) / perPoint);
  38. if (rms > maxRms) {
  39. maxRms = rms;
  40. maxFrame = frame;
  41. }
  42. if (Math.abs(midpoint) > maxMid) {
  43. maxMid = Math.abs(midpoint);
  44. }
  45. // Min value, max value, and midpoint value
  46. return [rms, midpoint];
  47. });
  48. return points;
  49. });
  50. var adjusted = unadjusted.map(function(frame){
  51. return frame.map(function(point){
  52. return [
  53. point[0] / maxRms,
  54. point[1] / maxMid
  55. ];
  56. });
  57. });
  58. // Make first and last frame peaky
  59. adjusted[0] = adjusted[numFrames - 1] = adjusted[maxFrame];
  60. return adjusted;
  61. }
  62. module.exports = getWaveform;