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

pcm.js 1.3KB

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