js实现tts
使用Web Speech API实现TTS
Web Speech API提供了浏览器内置的文本转语音(TTS)功能,无需额外依赖库。以下是一个基础实现示例:
// 创建语音合成对象
const synth = window.speechSynthesis;
// 获取浏览器支持的语音列表(可选)
const voices = synth.getVoices();
// 基础TTS函数
function speak(text, lang = 'en-US') {
if (synth.speaking) synth.cancel(); // 停止当前播放
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = lang; // 设置语言
utterance.rate = 1.0; // 语速(0.1-10)
utterance.pitch = 1.0; // 音高(0-2)
// 选择特定语音(可选)
if (voices.length > 0) {
const targetVoice = voices.find(voice =>
voice.lang.includes(lang)
);
if (targetVoice) utterance.voice = targetVoice;
}
synth.speak(utterance);
}
// 调用示例
speak('Hello world');
语音参数调整
可以修改SpeechSynthesisUtterance对象的属性来控制语音输出:
const utterance = new SpeechSynthesisUtterance();
utterance.text = '可调节参数的语音';
utterance.volume = 0.8; // 音量(0-1)
utterance.rate = 0.9; // 慢速
utterance.pitch = 1.5; // 高音调
utterance.lang = 'zh-CN'; // 中文
// 添加事件监听
utterance.onboundary = (e) => {
console.log(`到达边界: ${e.charIndex}处`);
};
多语言支持
通过切换lang属性支持不同语言:
// 英语
speak('Good morning', 'en-US');
// 中文
speak('早上好', 'zh-CN');
// 日语
speak('おはようございます', 'ja-JP');
浏览器兼容性处理
添加兼容性检查和错误处理:
function safeSpeak(text) {
if (!('speechSynthesis' in window)) {
console.error('浏览器不支持Web Speech API');
return;
}
try {
const utterance = new SpeechSynthesisUtterance(text);
window.speechSynthesis.speak(utterance);
} catch (e) {
console.error('语音合成失败:', e);
}
}
高级功能实现
实现队列系统和语音切换:
const speechQueue = [];
let isSpeaking = false;
function queueSpeak(text, options = {}) {
speechQueue.push({ text, options });
if (!isSpeaking) processQueue();
}
function processQueue() {
if (speechQueue.length === 0) {
isSpeaking = false;
return;
}
isSpeaking = true;
const { text, options } = speechQueue.shift();
const utterance = new SpeechSynthesisUtterance(text);
Object.assign(utterance, options);
utterance.onend = processQueue;
speechSynthesis.speak(utterance);
}
注意事项
- Chrome需要用户交互(如点击事件)后才能触发语音合成
- 移动端浏览器可能存在限制
- 语音列表需要等待
voiceschanged事件触发后才能获取完整列表 - 部分语言/方言需要操作系统支持对应语音包






