[JS30] Day20: Native Speech Recognition
tags: AI, contenteditable, note style, 語音辨識
這裡是使用內建在 Chrome 瀏覽器裡面的語音辨識 API,它存在 Chrome 瀏覽器的全域環境 window.webkitSpeechRecognition ,如果是使用其他瀏覽器可能要注意一下兼容性和使用方法。
contenteditable 屬性(HTML 部分)
這裡的 HTML 多了一個叫做 contenteditable 的屬性,這個屬性可以設成 true/false 告訴瀏覽器這個區塊是不是使用者可以編輯的,在 Chrome 只要加上這個屬性之後,原本的 div 就會變成像 input 區塊一樣,使用者可以在裡面隨意編輯,非常有趣:
<div class="words" contenteditable="true"></div>
在原本的教學影片中,只在
<div>裡面加上contenteditable這個屬性,而沒有指定true/false,這點在 MDN contenteditable 的說明中指出,因為 contenteditable 是可列舉的屬性,因此建議還是要給它值。
語音辨識 API - speechRecognition(JS 部分)
初始化 API
初始化語音辨識 API:
let recognition = new webkitSpeechRecognition();
這個 API 提供一些參數可以讓我們設定:
lang:可以到 Web Speech API Demonstration 中透過檢視網頁原始碼看其他支援的語系。interimResults:設成 true 表示在講話的當下會即時辨識,不需要等待。continuous:設成 true 表示除非使用者停止,否則會一直辨識,不會結束;false 的話則是講完一段話停頓時就會停止辨識。
recognition.interimResults = true; // 講話的當下即時辨識
recognition.lang = 'cmn-Hant-TW'; // 要辨識的語言
recognition.continuous = false; // 會自動結束辨識