Skip to content

Commit

Permalink
nodejs fix: mic example not working alphacep#1203
Browse files Browse the repository at this point in the history
  • Loading branch information
BrunoHenrique00 committed Mar 24, 2023
1 parent 9cee289 commit 0b8e904
Showing 1 changed file with 51 additions and 36 deletions.
87 changes: 51 additions & 36 deletions nodejs/demo/test_microphone.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,61 @@
var vosk = require('..')

const fs = require("fs");
var mic = require("mic");

MODEL_PATH = "model"
SAMPLE_RATE = 16000
const vosk = require('..');
const fs = require('fs');
const { spawn } = require('child_process');
const { platform } = require('os');

const MODEL_PATH = 'model';
const SAMPLE_RATE = 16000;
const soxInputPlatformDic = {
win32: 'waveaudio',
linux: 'pulseaudio',
darwin: 'coreaudio',
};

if (!fs.existsSync(MODEL_PATH)) {
console.log("Please download the model from https://alphacephei.com/vosk/models and unpack as " + MODEL_PATH + " in the current folder.")
process.exit()
console.log(
'Please download the model from https://alphacephei.com/vosk/models and unpack as ' +
MODEL_PATH +
' in the current folder.',
);
process.exit();
}

vosk.setLogLevel(0);
vosk.setLogLevel(1);
const model = new vosk.Model(MODEL_PATH);
const rec = new vosk.Recognizer({model: model, sampleRate: SAMPLE_RATE});

var micInstance = mic({
rate: String(SAMPLE_RATE),
channels: '1',
debug: false,
device: 'default',
const rec = new vosk.Recognizer({ model: model, sampleRate: SAMPLE_RATE });

// Install Sox before using this example: https://sourceforge.net/projects/sox/files/sox/
const soxProcess = spawn(`sox`, [
'-b',
'16',
'--endian',
'little',
'-c',
'1',
'-r',
'16k',
'-e',
'signed-integer',
'-t',
soxInputPlatformDic[platform],
'default',
'-t',
'wav',
'-',
]);

// Pass audio (data) into the Vosk API
soxProcess.stdout.on('data', data => {
if (rec.acceptWaveform(data)) console.log(rec.result());
else console.log(rec.partialResult());
});

var micInputStream = micInstance.getAudioStream();

micInputStream.on('data', data => {
if (rec.acceptWaveform(data))
console.log(rec.result());
else
console.log(rec.partialResult());
// Handle errors of Sox instance
soxProcess.on('error', error => {
console.log('Error executing Sox: ', error.message);
});

micInputStream.on('audioProcessExitComplete', function() {
console.log("Cleaning up");
console.log(rec.finalResult());
rec.free();
model.free();
process.on('SIGINT', function () {
console.log('\nStopping');
soxProcess.kill('SIGTERM');
});

process.on('SIGINT', function() {
console.log("\nStopping");
micInstance.stop();
});

micInstance.start();

0 comments on commit 0b8e904

Please sign in to comment.