HTML5 Web Speech API:语音识别与合成功能开发
HTML5 Web Speech API 提供了浏览器内置的语音识别(SpeechRecognition)和语音合成(SpeechSynthesis)功能,无需依赖第三方库。语音识别(SpeechRecognition):将用户的语音转换为文本。语音合成(SpeechSynthesis):将文本转换为语音输出。
·
HTML5 Web Speech API 概述
HTML5 Web Speech API 提供了浏览器内置的语音识别(SpeechRecognition)和语音合成(SpeechSynthesis)功能,无需依赖第三方库。该 API 分为两部分:
- 语音识别(SpeechRecognition):将用户的语音转换为文本。
- 语音合成(SpeechSynthesis):将文本转换为语音输出。
语音识别(SpeechRecognition)
语音识别通过 SpeechRecognition 接口实现,需注意浏览器兼容性(Chrome、Edge 支持较好)。
基本实现步骤
创建 SpeechRecognition 实例并配置参数:
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.lang = 'zh-CN'; // 设置语言
recognition.interimResults = true; // 返回临时识别结果
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
console.log('识别结果:', transcript);
};
recognition.start(); // 启动识别
关键配置项
continuous:是否持续监听语音(默认false,识别一次后停止)。maxAlternatives:返回的候选识别结果数量(默认1)。onerror:处理识别错误(如权限拒绝或网络问题)。
兼容性处理
使用 webkit 前缀兜底:
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
语音合成(SpeechSynthesis)
通过 SpeechSynthesis 接口实现文本转语音。
基本实现步骤
创建 SpeechSynthesisUtterance 对象并设置属性:
const utterance = new SpeechSynthesisUtterance('你好,世界');
utterance.lang = 'zh-CN'; // 设置语言
utterance.rate = 1.0; // 语速(0.1-10)
utterance.pitch = 1.0; // 音高(0-2)
window.speechSynthesis.speak(utterance); // 播放语音
控制语音播放
speechSynthesis.pause():暂停合成。speechSynthesis.resume():恢复合成。speechSynthesis.cancel():停止合成。
获取可用语音列表
通过 speechSynthesis.getVoices() 获取浏览器支持的语音列表:
speechSynthesis.getVoices().forEach(voice => {
console.log(voice.name, voice.lang);
});
实际应用示例
语音输入表单
结合语音识别实现语音输入:
<input type="text" id="speech-input" placeholder="点击按钮说话">
<button id="start-btn">开始录音</button>
<script>
const startBtn = document.getElementById('start-btn');
const input = document.getElementById('speech-input');
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.lang = 'zh-CN';
recognition.onresult = (event) => {
input.value = event.results[0][0].transcript;
};
startBtn.addEventListener('click', () => recognition.start());
</script>
语音朗读页面内容
通过语音合成朗读选中的文本:
document.addEventListener('selectionchange', () => {
const selectedText = window.getSelection().toString();
if (selectedText) {
const utterance = new SpeechSynthesisUtterance(selectedText);
speechSynthesis.speak(utterance);
}
});
注意事项
- 用户权限:首次使用时浏览器会请求麦克风权限。
- HTTPS 环境:部分浏览器要求 API 在安全上下文(HTTPS)中运行。
- 兼容性检查:使用前检测 API 支持情况:
if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) { alert('当前浏览器不支持语音识别'); }
通过合理配置事件监听和错误处理,可以构建更健壮的语音交互功能。
更多推荐
所有评论(0)