serenadeai / speech-recorder

speech-recorder is a node.js module for streaming audio from a device's microphone and filtering for speech.
MIT License
87 stars 20 forks source link

Speech Recorder

speech-recorder is a cross-platform, native node.js addon for getting a stream of audio from a device's microphone. Using speech-recorder, you can also get only the audio that corresponds to someone speaking.

This module is used for speech recognition in Serenade. Serenade enables you to write code through natural speech, rather than typing.

Installation

speech-recorder has been tested on Windows 10, macOS 10.14+, and Ubuntu 18.04+ (and may work on other platforms as well).

To install speech-recorder, run:

yarn add speech-recorder

If you're using this library with Electron, you should probably use electron-rebuild.

Usage

This library uses two voice activity detection mechanisms: a fast first pass (the WebRTC VAD), and a slightly slower, but much more accurate, second pass (the Silero VAD). See below for the various options you can supply to each.

Streaming

When you start recording, you can register various callbacks. onAudio is called when any audio comes in from the microphone. onChunkStart is called when a chunk of speech begins, and onChunkEnd is called when speech ends.

const { SpeechRecorder } = require("speech-recorder");

const recorder = new SpeechRecorder({
  onChunkStart: ({ audio }) => {
    console.log(Date.now(), "Chunk start");
  },
  onAudio: ({ speaking, probability, volume }) => {
    console.log(Date.now(), speaking, probability, volume);
  },
  onChunkEnd: () => {
    console.log(Date.now(), "Chunk end");
  },
});

console.log("Recording for 5 seconds...");
recorder.start();
setTimeout(() => {
  console.log("Done!");
  recorder.stop();
}, 5000);

You can write all audio from the microphone to a file with:

const { SpeechRecorder } = require("speech-recorder");

const writeStream = fs.createWriteStream("audio.raw");
const recorder = new SpeechRecorder({
  onAudio: ({ audio }) => {
    writeStream.write(audio);
  }
});

Or, just the speech with:

const { SpeechRecorder } = require("speech-recorder");

const writeStream = fs.createWriteStream("audio.raw");
const recorder = new SpeechRecorder({
  onAudio: ({ audio, speech }) => {
    if (speech) {
      writeStream.write(audio);
    }
  }
});

Devices

You can get a list of supported devices with:

const { devices } = require("speech-recorder");

console.log(devices());

Options

Building SpeechRecorder

If you want to build speech-recorder from source, first install the necessary dependencies by running:

./setup.sh <arch>

Where <arch> specifies the architecture you'd like to build for and is one of x86, x64, or arm64. If you're not sure, you probably want x64.

Then, you can build speech-recorder with:

./build.sh <arch>