語音產生文字功能
此功能的關鍵 API 是 Web Speech API,具體來說是 SpeechRecognition API。在你的程式碼中,webkitSpeechRecognition 是 Web Speech API 的一部分,負責語音辨識,將語音轉換為文字。
關鍵 API 介紹
-
webkitSpeechRecognition(或SpeechRecognition):- 用於語音辨識。
- 需透過 JavaScript 啟動並監聽語音輸入。
-
主要屬性
recognition.lang = "zh-TW";
設定語言為繁體中文(台灣)。recognition.continuous = true;
允許連續語音輸入,不會在一句話結束後停止辨識。recognition.interimResults = true;
啟用即時辨識,可顯示尚未確認的臨時結果。
-
事件監聽
recognition.onstart:開始監聽時觸發。recognition.onresult:當有語音輸入並轉換為文字時觸發。recognition.onerror:發生錯誤時觸發,例如權限被拒絕或麥克風無法使用。
其他 Web Speech API 相關功能
Web Speech API 其實包含兩個主要部分:
- SpeechRecognition API(語音辨識):將語音轉換成文字。
- SpeechSynthesis API(語音合成):將文字轉換成語音(TTS)。
你的程式碼主要使用 SpeechRecognition API 來進行語音轉文字。若要讓網頁朗讀文字,可以使用 SpeechSynthesis API,例如:
const synth = window.speechSynthesis;
const utterance = new SpeechSynthesisUtterance("你好,這是語音合成測試");
utterance.lang = "zh-TW";
synth.speak(utterance);
這樣就能讓網頁讀出「你好,這是語音合成測試」。
總結
你這段程式碼的關鍵 API 是:
SpeechRecognition(或webkitSpeechRecognition)- 主要用於語音辨識,將語音轉換為文字。
- 屬於 Web Speech API,適用於 Chrome 和 Edge(部分瀏覽器可能不支援)。
- 若要支援語音朗讀,可額外使用
SpeechSynthesis。
如果要讓語音辨識功能更完善,你可以:
- 增加停止辨識的按鈕
recognition.stop(); - 優化錯誤處理,例如
event.error === 'network'提示網路錯誤
這樣可以讓你的語音辨識應用更完整! 🚀
