27 lines
831 B
JavaScript
Raw Normal View History

2026-01-11 18:27:51 +08:00
export function initVoice(panel, onResultCallback) {
2026-01-02 21:06:54 +08:00
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
2026-01-11 18:27:51 +08:00
if (!SpeechRecognition) return { supportSpeech: false };
2026-01-02 21:06:54 +08:00
2026-01-11 18:27:51 +08:00
const recognition = new SpeechRecognition();
recognition.lang = "zh-CN";
2026-01-22 13:43:59 +08:00
recognition.continuous = false;
2026-01-11 18:27:51 +08:00
recognition.interimResults = false;
2026-01-02 21:06:54 +08:00
2026-01-11 18:27:51 +08:00
recognition.onresult = (event) => {
const text = event.results[0][0].transcript.trim();
if (text) {
2026-01-22 13:43:59 +08:00
console.log("识别结果:", text);
2026-01-11 18:27:51 +08:00
onResultCallback(text);
2026-01-02 21:06:54 +08:00
}
2026-01-11 18:27:51 +08:00
};
recognition.onerror = (event) => {
if (event.error !== 'aborted') console.error("语音错误:", event.error);
};
2026-01-02 21:06:54 +08:00
2026-01-11 18:27:51 +08:00
return {
supportSpeech: true,
start: () => { try { recognition.start(); } catch(e){} },
stop: () => { try { recognition.stop(); } catch(e){} }
};
2026-01-02 21:06:54 +08:00
}