stream-to-alsa.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. // replace username and password with speech to text credentials
  3. // audio.wav can be found here: https://github.com/watson-developer-cloud/nodejs-wrapper/blob/master/test/resources/audio.wav?raw=true
  4. var fs = require('fs');
  5. var opus = require('node-opus');
  6. var ogg = require('ogg');
  7. var cp = require('child_process');
  8. var oggDecoder = new ogg.Decoder();
  9. oggDecoder.on('stream', function (stream) {
  10. var opusDecoder = new opus.Decoder();
  11. // the "format" event contains the raw PCM format
  12. opusDecoder.on('format', function (format) {
  13. // format example:
  14. //{
  15. // channels: 1,
  16. // sampleRate: 24000,
  17. // bitDepth: 16,
  18. // float: false,
  19. // signed: true,
  20. // gain: 0,
  21. // preSkip: 156,
  22. // version: 1
  23. //}
  24. // convert the signed & bitDepth to an alsa compatible format (`aplay --help format` for full list)
  25. var alsaFormat;
  26. if (format.signed && format.bitDepth == 16) {
  27. alsaFormat = 'S16_LE'; // assume Little Endian
  28. } else {
  29. throw new Error('unexpected format: ' + JSON.stringify(format));
  30. }
  31. // set up aplay to accept data from stdin
  32. var aplay = cp.spawn('aplay',['--format=' + alsaFormat, '--rate=' + format.sampleRate, '--channels='+format.channels, '--']);
  33. // send the raw PCM data to aplay
  34. opusDecoder.pipe(aplay.stdin);
  35. // or pipe to node-speaker, a file, etc
  36. });
  37. // an "error" event will get emitted if the stream is not a Vorbis stream
  38. // (i.e. it could be a Theora video stream instead)
  39. opusDecoder.on('error', console.error);
  40. stream.pipe(opusDecoder);
  41. });
  42. fs.createReadStream('input.opus').pipe(oggDecoder);