浏览器端只需要这几句话就可以实现文本变成语音播报

function text2Voice(){
    let synth = window.speechSynthesis;
    let utterThis = new SpeechSynthesisUtterance(text);
    synth.speak(utterThis);
}

text2Voice('支付宝到账5元');

html演示

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文本转语音示例</title>
    <style>
        /* 页面样式,可按需自定义 */
        body { font-family: Arial, sans-serif; }
        #textArea, #speakBtn { margin-bottom: 1em; }
    </style>
</head>
<body>
    <h1>JavaScript文本转语音演示</h1>
    <textarea id="textArea" rows="4" cols="50" placeholder="请输入要转换为语音的文本..."></textarea>
    <button id="speakBtn">播放语音</button>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            var textArea = document.getElementById('textArea');
            var speakBtn = document.getElementById('speakBtn');

            speakBtn.addEventListener('click', function() {
                var textToSpeak = textArea.value.trim();

                // 创建新的SpeechSynthesisUtterance对象
                var utterance = new SpeechSynthesisUtterance(textToSpeak);
                utterance.lang = 'zh-CN'; // 设置语言为中文(简体)

                // 添加到语音合成队列中
                speechSynthesis.speak(utterance);

                // 可选,添加事件监听器
                utterance.onend = function(e) {
                    console.log('语音播放完毕');
                };
            });
        });
    </script>
</body>
</html>

老段
0 声望0 粉丝