前端文字转语音
html
<!DOCTYPE html>
<html lang="zh-CN">
<body>
<textarea id="text" rows="4" cols="40">你好,这是网页端文字转语音。</textarea>
<br><br>
<button onclick="speak()">播放</button>
<script>
function speak() {
const text = document.getElementById('text').value;
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = 'zh-CN';
utterance.rate = 1; // 语速
utterance.pitch = 1; // 音调
// 1. 声明 window 上可能存在 webkitAudioContext
const AudioContext = window.AudioContext || (window as any).webkitAudioContext;
// 2. 使用声明好的变量创建上下文
const audioContext = new AudioContext();
// --- 关键修改结束 ---
const gainNode = audioContext.createGain();
gainNode.gain.value = 2.0; // 音量放大 2 倍(可调)
speechSynthesis.speak(utterance);
}
</script>
</body>
</html>
语言代码 语言
zh-CN 中文
en-US 英语(美国)
en-GB 英语(英国)
ja-JP 日语
ko-KR 韩语
es-ES 西班牙语
fr-FR 法语
de-DE 德语