js实现文字转语音
实现文字转语音的方法
在JavaScript中,可以通过Web Speech API实现文字转语音(TTS)功能。以下是一个简单的实现方法:
// 创建SpeechSynthesisUtterance对象
const utterance = new SpeechSynthesisUtterance();
utterance.text = "这是要转换为语音的文字内容";
// 设置语音参数(可选)
utterance.rate = 1; // 语速 (0.1-10)
utterance.pitch = 1; // 音高 (0-2)
utterance.volume = 1; // 音量 (0-1)
// 获取可用的语音列表并选择(可选)
const voices = window.speechSynthesis.getVoices();
utterance.voice = voices[0]; // 选择第一个可用语音
// 播放语音
window.speechSynthesis.speak(utterance);
完整示例代码
<!DOCTYPE html>
<html>
<head>
<title>文字转语音示例</title>
</head>
<body>
<textarea id="textToSpeak" rows="4" cols="50">输入要转换为语音的文字</textarea>
<br>
<button onclick="speak()">朗读</button>
<button onclick="stop()">停止</button>
<script>
function speak() {
const text = document.getElementById('textToSpeak').value;
const utterance = new SpeechSynthesisUtterance(text);
// 可选:设置语音参数
utterance.rate = 1;
utterance.pitch = 1;
window.speechSynthesis.speak(utterance);
}
function stop() {
window.speechSynthesis.cancel();
}
</script>
</body>
</html>
注意事项
浏览器兼容性:Web Speech API在现代浏览器中得到良好支持,包括Chrome、Firefox、Edge和Safari,但在旧版浏览器中可能不可用。

语音加载:某些浏览器可能需要等待语音引擎加载完成。可以监听voiceschanged事件:

window.speechSynthesis.onvoiceschanged = function() {
const voices = window.speechSynthesis.getVoices();
// 现在可以安全地选择语音
};
高级用法
可以创建更复杂的TTS应用,包括:
- 语音选择下拉菜单
- 语速、音高和音量控制滑块
- 多语言支持
- 语音队列管理
// 语音选择示例
function populateVoiceList() {
const voices = window.speechSynthesis.getVoices();
const voiceSelect = document.getElementById('voiceSelect');
voices.forEach((voice, i) => {
const option = document.createElement('option');
option.textContent = `${voice.name} (${voice.lang})`;
option.setAttribute('data-voice-index', i);
voiceSelect.appendChild(option);
});
}
// 在voiceschanged事件中调用
window.speechSynthesis.onvoiceschanged = populateVoiceList;
替代方案
如果Web Speech API不满足需求,可以考虑:
- 使用第三方TTS API服务
- 后端TTS解决方案
- 专门的TTS JavaScript库
这些方法通常需要网络连接或服务器支持,但可能提供更高质量的语音输出。





