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

pcm.js 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. var spawn = require("child_process").spawn,
  2. stream = require("stream");
  3. // Based on https://github.com/jhurliman/node-pcm
  4. // Modified to respect channels, use fewer vars, and return a stream
  5. module.exports = function(filename, options) {
  6. var sampleStream = new stream.Stream(),
  7. channels = 2,
  8. output = "",
  9. channel = 0,
  10. oddByte;
  11. sampleStream.readable = true;
  12. if (options && options.channels) channels = options.channels;
  13. var args = ["-i", filename, "-f", "s16le", "-ac", channels, "-acodec", "pcm_s16le"];
  14. if (options && options.sampleRate) {
  15. args.push("-ar", options.sampleRate);
  16. }
  17. args.push("-y", "pipe:1");
  18. var spawned = spawn("ffmpeg", args);
  19. spawned.stdout.on("data", function(data) {
  20. var len = data.length;
  21. if (oddByte != null) {
  22. sampleStream.emit("data", ((data.readInt8(i++, true) << 8) | oddByte) / 32767.0, channel);
  23. channel = ++channel % channels;
  24. }
  25. for (var i = 0; i < len; i += 2) {
  26. sampleStream.emit("data", data.readInt16LE(i, true) / 32767.0, channel);
  27. channel = ++channel % channels;
  28. }
  29. oddByte = (i < len) ? data.readUInt8(i, true) : null;
  30. });
  31. spawned.stderr.on("data", function(data) {
  32. output += data.toString();
  33. });
  34. spawned.stderr.on("end", function() {
  35. sampleStream.emit(oddByte !== undefined ? "end" : "error", output);
  36. });
  37. return sampleStream;
  38. };