【工具】HTML自动识别用户正在讲话 以及停止讲话
javascript
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>语音识别</title>
</head>
<body>
<h2>点击按钮开始语音识别</h2>
<button id="startButton">开始识别</button>
<p id="status">等待用户讲话...</p>
<script>
let recognition;
let isRecognizing = false;
// 检查浏览器是否支持 Web Speech API
if (!('webkitSpeechRecognition' in window)) {
alert("抱歉,您的浏览器不支持语音识别!");
} else {
recognition = new webkitSpeechRecognition();
recognition.continuous = true; // 设置为持续模式,识别一段时间后不会停止
recognition.interimResults = true; // 获取中间结果
// 语音识别开始时
recognition.onstart = function() {
isRecognizing = true;
document.getElementById('status').innerText = "正在识别中...";
};
// 语音识别结束时
recognition.onend = function() {
isRecognizing = false;
document.getElementById('status').innerText = "停止识别,等待用户讲话...";
};
// 识别到语音时
recognition.onresult = function(event) {
let result = event.results[event.resultIndex];
let transcript = result[0].transcript; // 获取识别的文本
console.log("识别结果:", transcript);
// 如果有中间结果,可以实时更新
if (event.results[0].isFinal) {
document.getElementById('status').innerText = "识别结果: " + transcript;
}
};
// 点击按钮开始识别
document.getElementById('startButton').addEventListener('click', function() {
if (isRecognizing) {
recognition.stop(); // 停止识别
document.getElementById('status').innerText = "已停止识别。";
} else {
recognition.start(); // 开始识别
}
});
}
</script>
</body>
</html>