前端想要实现语音转文字,其实不需要任何云服务,浏览器自带的api就能搞定。
下面是已经封装好的代码,
复制之后可以在控制台只接运行。
class SpeechRecognitionManager {
tempTranscript = ''
isRecording = false;
timeoutid = 0;
exitKeywors = ['stop', 'exit', 'quit', '退出', '停止识别', '说完了', '停止', '发送', '好了']
constructor() {
this.recognition = new webkitSpeechRecognition();
this.recognition.continuous = true;
this.recognition.interimResultsTimeout = 30000;
this.recognition.lang = 'zh-CN';
this.recognition.maxSpeechTime = 60000;
this.resultListeners = [];
this.recognition.onresult = (event) => {
const transcript = Array.from(event.results).at(-1)[0].transcript;
clearTimeout(this.timeoutid);
if (this.exitKeywors.some(keyword => transcript.includes(keyword) && transcript.length <= 7)) {
this.recognition.stop();
// this.isRecording = false;
// this.notifyResultListeners({
// transcript: this.tempTranscript,
// type: 'end',
// });
return;
}
this.timeoutid = setTimeout(() => {
this.recognition.stop();
}, 4000);
this.tempTranscript += transcript;
this.notifyResultListeners({
transcript,
type: 'tempresult',
});
};
this.recognition.onend = () => {
this.isRecording = false;
this.notifyResultListeners({
type: 'end',
transcript: this.tempTranscript
});
};
this.recognition.onerror = (event) => {
this.isRecording = false;
this.notifyResultListeners({
type: 'error',
transcript: this.tempTranscript,
error: event.error
});
};
this.recognition.onstart = () => {
this.isRecording = true;
this.tempTranscript = '';
this.notifyResultListeners({
type: 'start'
});
};
}
addResultListener(listener) {
this.resultListeners.push(listener);
}
notifyResultListeners(data) {
this.resultListeners.forEach(listener => {
listener(data);
});
}
startRecognition() {
if (this.isRecording) return console.log('正在识别');
console.log('开始识别');
this.tempTranscript = '';
this.recognition.start();
}
stopRecognition() {
if (!this.isRecording) return console.log('未开始识别');
this.isRecording = false;
console.log('停止识别');
this.recognition.stop();
}
}
// 使用示例
window.speechmanager = new SpeechRecognitionManager();
// // 添加结果监听函数
// speechmanager.addResultListener(transcript => {
// console.log('识别结果:', transcript);
// });
// // 开始识别
// speechmanager.startRecognition();
// // // 停止识别
// // // manager.stopRecognition();