Browse Source

PCM reader

Noah 7 years ago
parent
commit
5c61939740
1 changed files with 54 additions and 0 deletions
  1. 54 0
      lib/pcm.js

+ 54 - 0
lib/pcm.js View File

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