36 lines
1.0 KiB
JavaScript
36 lines
1.0 KiB
JavaScript
// 语音识别
|
|
|
|
export function initVoice(panel, handleCommand) {
|
|
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
|
|
const supportSpeech = !!SpeechRecognition;
|
|
let recognition;
|
|
|
|
if (supportSpeech) {
|
|
recognition = new SpeechRecognition();
|
|
recognition.lang = "zh-CN";
|
|
recognition.continuous = false;
|
|
recognition.interimResults = false;
|
|
|
|
recognition.onresult = (event) => {
|
|
const text = event.results[0][0].transcript.trim();
|
|
handleCommand(text);
|
|
};
|
|
|
|
recognition.onerror = (event) => {
|
|
console.error("语音识别错误", event.error);
|
|
};
|
|
|
|
panel.querySelector("#voiceBtn").onclick = () => recognition.start();
|
|
} else {
|
|
panel.querySelector("#voiceBtn").disabled = true;
|
|
panel.querySelector("#voiceBtn").innerText = "❌";
|
|
}
|
|
|
|
document.addEventListener("keydown", (e) => {
|
|
if (e.altKey && e.key.toLowerCase() === "v" && supportSpeech && recognition) {
|
|
recognition.start();
|
|
}
|
|
});
|
|
|
|
return supportSpeech;
|
|
} |