2025-10-22 22:34:45【零成本语音交互方案】Web Speech API 实战:手把手实现文本朗读与语音输入
🌟 一、技术全景:Web Speech API 双刃剑
官网链接: 点击跳转 文本转语音 (TTS):将文字转换为自然语音播放,适用于语音提示、无障碍阅读 语音转文本 (STT):通过麦克风捕捉语音并实时转文字,适用于语音搜索、会议记录
🎙️ 二、文本转语音(TTS)实现
核心对象:SpeechSynthesis 兼容性:Chrome 33+、Edge 79+、Safari 7+(部分功能受限)
// 1. 基础播放
function speak(text) {
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = 'zh-CN'; // 设置语言
utterance.rate = 1; // 语速 0.1-10
utterance.pitch = 1; // 音高 0-2
speechSynthesis.speak(utterance);
}
// 2. 获取可用语音列表
speechSynthesis.getVoices().forEach(voice => {
console.log(`${voice.name} (${voice.lang})`);
});
// 3. 高级控制
const speechControl = {
pause: () => speechSynthesis.pause(),
resume: () => speechSynthesis.resume(),
cancel: () => speechSynthesis.cancel()
};
🎤 三、语音转文本(STT)实现
核心对象:SpeechRecognition 兼容性:Chrome 47+(需HTTPS)、Edge 79+
// 1. 初始化识别器
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.lang = 'zh-CN'; // 设置语言
recognition.interimResults = true; // 实时返回中间结果
recognition.continuous = false; // 单次识别模式
// 2. 事件监听
recognition.onresult = (event) => {
const transcript = Array.from(event.results)
.map(result => result[0].transcript)
.join('');
console.log('识别结果:', transcript);
};
recognition.onerror = (event) => {
console.error('识别错误:', event.error);
};
// 3. 控制方法
const sttControl = {
start: () => recognition.start(),
stop: () => recognition.stop()
};
// 4. 获取麦克风权限
navigator.mediaDevices.getUserMedia({ audio: true })
.then(() => console.log('麦克风已授权'))
.catch(err => console.error('麦克风访问被拒绝:', err));
🔧 四、实战增强功能
1. TTS播放队列管理
const speechQueue = [];
let isSpeaking = false;
function addToQueue(text) {
speechQueue.push(text);
if (!isSpeaking) processQueue();
}
function processQueue() {
if (speechQueue.length === 0) {
isSpeaking = false;
return;
}
isSpeaking = true;
const utterance = new SpeechSynthesisUtterance(speechQueue.shift());
utterance.onend = processQueue;
speechSynthesis.speak(utterance);
}
2. STT关键词唤醒
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript.toLowerCase();
if (transcript.includes('小助手')) {
console.log('唤醒成功!');
// 执行后续操作...
}
};
⚠️ 五、关键问题与解决方案
问题解决方案移动端兼容性差使用第三方库(如annyang)兜底Chrome本地文件限制必须通过HTTPS协议或localhost访问语音包体积过大动态加载语言包:recognition.lang = navigator.language长时间识别内存泄漏设置continuous: false,每次识别后重启实例中文识别准确率低接入百度语音API混合方案(免费版5万次/日)
🌐 六、备选方案推荐
第三方TTS服务
Azure Cognitive Services
阿里云智能语音交互
开源STT库
TensorFlow.js Speech Commands
Mozilla DeepSpeech
“语音交互不是未来科技,而是当下可立即落地的用户体验升级点!” 立即尝试本文方案,为你的应用装上「声音的翅膀」吧! 🚀