Web Speech API 可在浏览器中实现语音识别,通过创建 SpeechRecognition 实例并配置语言、连续识别等参数,结合 onresult 等事件获取语音转文本结果,示例代码展示了在 Chrome 浏览器中点击按钮开始录音、实时显示识别内容的功能,需注意该 API 仅支持 HTTPS 或 localhost,且主要在桌面版 Chrome 中可用,其他浏览器兼容性有限,使用时需处理错误和权限授权,并为不支持的用户提供降级提示。

HTML5 本身不直接提供语音识别功能,但可以通过 Web Speech API 实现语音识别。该 API 提供了浏览器端的语音识别和语音合成功能,其中 SpeechRecognition 接口用于将用户的语音转换为文本。
目前,Web Speech API 的语音识别接口在部分浏览器中需要通过前缀调用,且主要在 Chrome 浏览器中支持较好(如 Chrome 25+)。以下是实现步骤:
SpeechRecognition 或 webkitSpeechRecognition 实例以下是一个完整的简单示例,点击按钮开始语音识别,识别结果实时显示在页面上:
立即学习“前端免费学习笔记(深入)”;
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>语音识别测试</title>
</head>
<body>
<h2>语音识别(Web Speech API)</h2>
<button id="startBtn">开始录音</button>
<button id="stopBtn">停止录音</button>
<div id="result">识别结果将显示在这里...</div>
<script>
// 检查浏览器是否支持 Web Speech API
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SpeechRecognition) {
document.getElementById('result').textContent = '当前浏览器不支持语音识别,请使用 Chrome 浏览器。';
const startBtn = document.getElementById('startBtn');
startBtn.disabled = true;
return;
}
// 创建识别实例
const recognition = new SpeechRecognition();
recognition.lang = 'zh-CN'; // 设置语言为中文
recognition.continuous = true; // 是否持续监听
recognition.interimResults = true; // 是否返回中间结果
const resultDiv = document.getElementById('result');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
// 绑定识别结果事件
recognition.onresult = (event) => {
let finalTranscript = '';
let interimTranscript = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
const transcript = event.results[i][0].transcript;
if (event.results[i].isFinal) {
finalTranscript += transcript;
} else {
interimTranscript += transcript;
}
}
// 显示最终结果 + 中间结果
resultDiv.innerHTML = `
<strong>最终结果:</strong>${finalTranscript}<br>
<em>正在识别:</em>${interimTranscript}
`;
};
// 错误处理
recognition.onerror = (event) => {
resultDiv.textContent += `\n识别出错:${event.error}`;
};
// 结束识别
recognition.onend = () => {
console.log('语音识别已结束');
};
// 开始识别
startBtn.onclick = () => {
recognition.start();
resultDiv.textContent = '正在聆听...';
};
// 停止识别
stopBtn.onclick = () => {
recognition.stop();
};
</script>
</body>
</html>以下是常用属性和事件的说明,帮助你更好地控制识别行为:
Web Speech API 目前存在一些限制:
基本上就这些。只要浏览器支持,Web Speech API 能快速实现语音转文字功能,适合做语音搜索、语音输入等轻量级应用。注意做好降级处理,提示不支持的用户更换浏览器或使用其他输入方式。
以上就是HTML5代码如何实现语音识别 HTML5代码中Web Speech API的调用的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号