Theme NexT works best with JavaScript enabled

ShunNien's Blog

不積跬步,無以致千里;不積小流,無以成江海。

0%

JS30紀錄 20-Speech Detection

目標

語音識別 API 操作,透過 SpeechRecognition 來進行語音辨識,並呈現文字

target

Demo | Github

處理步驟

步驟 1.

  • 啟動語音
1
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  • 宣告變數為語音辨識
1
const recognition = new SpeechRecognition();
  • 建立 p tag ,等下將辨識文字顯示在上
  • 啟用識別 recognition.start();
  • 當識別結束,重複識別
1
recognition.addEventListener("end", recognition.start);

參考資料
SpeechRecognition()
interimResults
SpeechRecognition event start
SpeechRecognition event end

步驟 2.

產生識別結果後,將文字呈現在 p tag 內容中,識別結果為 SpeechRecognitionResultList 取得 transcript 屬性,就是辨識文字

SpeechResult

當確認辨識結束,建立新的 p tag 元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
recognition.addEventListener("result", e => {
// 識別結果為 SpeechRecognitionResultList 取得 transcript 屬性,就是辨識文字
const transcript = Array.from(e.results)
.map(result => result[0])
.map(result => result.transcript)
.join("");

// 輸出辨識文字內容
p.textContent = transcript;

// 確認辨識結束,就產生新的 p 元素
if (e.results[0].isFinal) {
p = document.createElement("p");
words.appendChild(p);
}
});

參考資料
SpeechRecognition event result

步驟 3.

當辨識文字出現特定文字的時候,可以使用 replace 取代呈現。

1
2
3
// 特殊內容使用符號文字取代
const poopScript = transcript.replace(/poop|poo|shit|dump/gi, '💩');
p.textContent = poopScript;

筆記與備註事項

JavaScript 部分

SpeechRecognition()

實驗性功能,所以是尚未確定所有瀏覽器支援的功能。

SpeechRecognition.interimResults

此屬性為布林值,控制是否取得即時辨識結果,預設為 false

SpeechRecognition.start()

啟動語音識別服務

SpeechRecognition Events 觸發事件

以下為 Web Speech API 事件

result

語音辨識結束返回結果的時候觸發。

1
2
3
4
5
6
7
8
9
10
11
12
13
recognition.onresult = function(event) {
// The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
// The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
// It has a getter so it can be accessed like an array
// The first [0] returns the SpeechRecognitionResult at position 0.
// Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects that contain individual results.
// These also have getters so they can be accessed like arrays.
// The second [0] returns the SpeechRecognitionAlternative at position 0.
// We then return the transcript property of the SpeechRecognitionAlternative object
var color = event.results[0][0].transcript;
diagnostic.textContent = 'Result received: ' + color + '.';
bg.style.backgroundColor = color;
}

end

語音辨識服務結束時觸發。

1
2
3
4
5
var recognition = new SpeechRecognition();

recognition.onend = function() {
console.log('Speech recognition service disconnected');
}

參考資料

歡迎關注我的其它發布渠道