我遇到了一个基于React的应用程序出现的情况,我有一个我也想允许语音输入的输入。我可以使其仅与Chrome和Firefox兼容,因此我考虑使用getUserMedia。我知道我将使用Google Cloud的语音转文本API。但是,我有一些警告:
似乎没有地方提供有关如何执行此操作的很好的教程。我该怎么办?
答案 0 :(得分:7)
首先,应归功于信誉:我在这里的解决方案很大一部分是通过引用vin-ni的Google-Cloud-Speech-Node-Socket-Playground project创建的。但是,我不得不对我的React应用程序进行一些调整,因此,我要分享一些我所做的更改。
我的解决方案由四个部分组成,两个部分在前端,两个在后端。
我的前端解决方案包括两个部分:
我的后端解决方案包括两个部分:
main.js
文件(这些不需要任何分隔;我们的main.js
文件已经是没有它的庞然大物。)
我的大部分代码都将被摘录,但是我的实用程序将被完整显示,因为我涉及的所有阶段都存在很多问题。我的前端实用程序文件如下所示:
// Stream Audio
let bufferSize = 2048,
AudioContext,
context,
processor,
input,
globalStream;
//audioStream constraints
const constraints = {
audio: true,
video: false
};
let AudioStreamer = {
/**
* @param {function} onData Callback to run on data each time it's received
* @param {function} onError Callback to run on an error if one is emitted.
*/
initRecording: function(onData, onError) {
socket.emit('startGoogleCloudStream', {
config: {
encoding: 'LINEAR16',
sampleRateHertz: 16000,
languageCode: 'en-US',
profanityFilter: false,
enableWordTimeOffsets: true
},
interimResults: true // If you want interim results, set this to true
}); //init socket Google Speech Connection
AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
processor = context.createScriptProcessor(bufferSize, 1, 1);
processor.connect(context.destination);
context.resume();
var handleSuccess = function (stream) {
globalStream = stream;
input = context.createMediaStreamSource(stream);
input.connect(processor);
processor.onaudioprocess = function (e) {
microphoneProcess(e);
};
};
navigator.mediaDevices.getUserMedia(constraints)
.then(handleSuccess);
// Bind the data handler callback
if(onData) {
socket.on('speechData', (data) => {
onData(data);
});
}
socket.on('googleCloudStreamError', (error) => {
if(onError) {
onError('error');
}
// We don't want to emit another end stream event
closeAll();
});
},
stopRecording: function() {
socket.emit('endGoogleCloudStream', '');
closeAll();
}
}
export default AudioStreamer;
// Helper functions
/**
* Processes microphone data into a data stream
*
* @param {object} e Input from the microphone
*/
function microphoneProcess(e) {
var left = e.inputBuffer.getChannelData(0);
var left16 = convertFloat32ToInt16(left);
socket.emit('binaryAudioData', left16);
}
/**
* Converts a buffer from float32 to int16. Necessary for streaming.
* sampleRateHertz of 1600.
*
* @param {object} buffer Buffer being converted
*/
function convertFloat32ToInt16(buffer) {
let l = buffer.length;
let buf = new Int16Array(l / 3);
while (l--) {
if (l % 3 === 0) {
buf[l / 3] = buffer[l] * 0xFFFF;
}
}
return buf.buffer
}
/**
* Stops recording and closes everything down. Runs on error or on stop.
*/
function closeAll() {
// Clear the listeners (prevents issue if opening and closing repeatedly)
socket.off('speechData');
socket.off('googleCloudStreamError');
let tracks = globalStream ? globalStream.getTracks() : null;
let track = tracks ? tracks[0] : null;
if(track) {
track.stop();
}
if(processor) {
if(input) {
try {
input.disconnect(processor);
} catch(error) {
console.warn('Attempt to disconnect input failed.')
}
}
processor.disconnect(context.destination);
}
if(context) {
context.close().then(function () {
input = null;
processor = null;
context = null;
AudioContext = null;
});
}
}
此代码的主要重点(除了getUserMedia配置之外,该配置本身有点麻烦)是处理器的onaudioprocess
回调向该套接字发出了speechData
事件,将数据转换为Int16之后。我从上面的链接参考中所做的主要更改是替换了所有功能,以使用回调函数(由我的React组件使用)实际更新DOM,并添加了一些源代码中未包含的错误处理。
然后我可以通过使用以下命令在我的React组件中访问它:
onStart() {
this.setState({
recording: true
});
if(this.props.onStart) {
this.props.onStart();
}
speechToTextUtils.initRecording((data) => {
if(this.props.onUpdate) {
this.props.onUpdate(data);
}
}, (error) => {
console.error('Error when recording', error);
this.setState({recording: false});
// No further action needed, as this already closes itself on error
});
}
onStop() {
this.setState({recording: false});
speechToTextUtils.stopRecording();
if(this.props.onStop) {
this.props.onStop();
}
}
(我将实际数据处理程序作为对该组件的支持而传递)。
然后在后端,我的服务处理了main.js
中的三个主要事件:
// Start the stream
socket.on('startGoogleCloudStream', function(request) {
speechToTextUtils.startRecognitionStream(socket, GCSServiceAccount, request);
});
// Receive audio data
socket.on('binaryAudioData', function(data) {
speechToTextUtils.receiveData(data);
});
// End the audio stream
socket.on('endGoogleCloudStream', function() {
speechToTextUtils.stopRecognitionStream();
});
然后我的speechToTextUtils如下:
// Google Cloud
const speech = require('@google-cloud/speech');
let speechClient = null;
let recognizeStream = null;
module.exports = {
/**
* @param {object} client A socket client on which to emit events
* @param {object} GCSServiceAccount The credentials for our google cloud API access
* @param {object} request A request object of the form expected by streamingRecognize. Variable keys and setup.
*/
startRecognitionStream: function (client, GCSServiceAccount, request) {
if(!speechClient) {
speechClient = new speech.SpeechClient({
projectId: 'Insert your project ID here',
credentials: GCSServiceAccount
}); // Creates a client
}
recognizeStream = speechClient.streamingRecognize(request)
.on('error', (err) => {
console.error('Error when processing audio: ' + (err && err.code ? 'Code: ' + err.code + ' ' : '') + (err && err.details ? err.details : ''));
client.emit('googleCloudStreamError', err);
this.stopRecognitionStream();
})
.on('data', (data) => {
client.emit('speechData', data);
// if end of utterance, let's restart stream
// this is a small hack. After 65 seconds of silence, the stream will still throw an error for speech length limit
if (data.results[0] && data.results[0].isFinal) {
this.stopRecognitionStream();
this.startRecognitionStream(client, GCSServiceAccount, request);
// console.log('restarted stream serverside');
}
});
},
/**
* Closes the recognize stream and wipes it
*/
stopRecognitionStream: function () {
if (recognizeStream) {
recognizeStream.end();
}
recognizeStream = null;
},
/**
* Receives streaming data and writes it to the recognizeStream for transcription
*
* @param {Buffer} data A section of audio data
*/
receiveData: function (data) {
if (recognizeStream) {
recognizeStream.write(data);
}
}
};
(再次,您严格不需要此util文件,您当然可以根据获取凭据的方式将speechClient
作为const放在文件顶部;这就是我实现它的方式)
最后,这应该足以让您开始。我鼓励您在重用或修改此代码之前尽一切努力来理解此代码,因为它可能对您而言不是“开箱即用”的功能,但是与我发现的所有其他资源不同,这至少应该使您从头开始涉及项目的各个阶段。我希望这个答案能够防止其他人像我一样遭受痛苦。