使用 JavaScript 透過 Web Speech API 實現語音識別

建立專案

建立 index.html 檔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Web Speech API</h1>
<button id="startButton">Start</button>
<button id="stopButton">Stop</button>
<p>
Result: <span id="result"></span>
</p>
<script>
if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
// 設定語言
recognition.lang = 'zh-TW';
// 持續辨識
recognition.continuous = true;
// 返回臨時結果
recognition.interimResults = true;
// 辨識結果
recognition.onresult = (event) => {
let transcript = '';
for (let i = 0; i < event.results.length; i++) {
transcript += event.results[i][0].transcript;
}
document.getElementById('result').innerText = transcript;
};
// 開始辨識
document.getElementById('startButton').onclick = () => {
recognition.start();
document.getElementById('result').innerText = 'Listening...';
};
// 停止辨識
document.getElementById('stopButton').onclick = () => {
recognition.stop();
};
} else {
alert('Web Speech API is not supported.');
}
</script>
</body>
</html>

參考資料