mime-chat/testAudio.js
2021-02-03 18:01:48 -06:00

87 lines
1.9 KiB
JavaScript

const fs = require('fs');
const speech = require('@google-cloud/speech');
const portAudio = require('naudiodon');
const rs = fs.createReadStream('rawAudio.wav');
const WebSocket = require("ws")
const {Writable} = require('stream');
// Creates a client
const client = new speech.SpeechClient();
// connect to test server
const ws = new WebSocket("ws://localhost:8080");
// google cloud speech to text settings
const encoding = 'LINEAR16';
const sampleRateHertz = 44100;
const languageCode = 'en-US';
const audioChunks = [];
const audioInputStreamTransform = new Writable({
write(chunk, encoding, next) {
console.log(chunk);
audioChunks.push(chunk);
next();
},
final() {
console.log(audioChunks);
},
});
const config = {
encoding: encoding,
sampleRateHertz: sampleRateHertz,
languageCode: languageCode,
};
const request = {
config,
interimResults: true,
};
const speechCallback = (data) => {
console.log(
`Transcription: ${data.results[0].alternatives[0].transcript}`
);
}
const recognizeStream = client
.streamingRecognize(request)
.on('error', err => {
if (err.code === 11) {
// restartStream();
} else {
console.error('API request error ' + err);
}
})
.on('data', speechCallback);
// Create an instance of AudioIO with inOptions (defaults are as below), which will return a ReadableStream
const recorderOptions = {
channelCount: 1,
sampleFormat: portAudio.sampleFormat16Bit,
sampleRate: 16000,
deviceId: -1, // Use -1 or omit the deviceId to select the default device
closeOnError: false // Close the stream if an audio error is detected, if set false then just log the error
}
const ai = new portAudio.AudioIO({
inOptions: recorderOptions
});
// manipulate individual chunks as they're available
// const audioData = [];
// ai.on('data', (d) => {
// audioData.push(d.toString('binary'))
// })
ai.pipe(audioInputStreamTransform)
ai.start();
setTimeout(() => {
ai.quit();
}, 2000)