输入文字导出MP3语音

120 阅读1分钟

直接简单的运行打开就可以实现输入文字导出MP3语音

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文字转MP3</title>
</head>
<body>
    <textarea id="textInput" rows="10" cols="30" placeholder="请输入文字"></textarea><br>
    <button id="convertBtn">转换为MP3并下载</button>

    <script src="https://cdn.jsdelivr.net/npm/lamejs@latest/lame.min.js"></script>
    <script>
        document.getElementById('convertBtn').addEventListener('click', function() {
            const text = document.getElementById('textInput').value;
            if (!text) {
                alert('请输入文字。');
                return;
            }

            const synth = window.speechSynthesis;
            const utterance = new SpeechSynthesisUtterance(text);
            utterance.lang = 'zh-CN';  // 设置为中文

            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const dest = audioContext.createMediaStreamDestination();
            const recorder = new MediaRecorder(dest.stream);
            const source = audioContext.createMediaStreamSource(dest.stream);

            let mp3encoder = new lamejs.Mp3Encoder(1, audioContext.sampleRate, 128);
            let mp3Data = [];

            recorder.ondataavailable = function(event) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const float32Array = new Float32Array(e.target.result);
                    const int16Array = float32ToInt16(float32Array);
                    
                    const mp3buf = mp3encoder.encodeBuffer(int16Array);
                    if (mp3buf.length > 0) {
                        mp3Data.push(mp3buf);
                    }
                };
                reader.readAsArrayBuffer(event.data);
            };

            recorder.onstop = function() {
                const mp3buf = mp3encoder.flush();
                if (mp3buf.length > 0) {
                    mp3Data.push(mp3buf);
                }
                const mp3Blob = new Blob(mp3Data, { type: 'audio/mp3' });
                const mp3Url = URL.createObjectURL(mp3Blob);

                const link = document.createElement('a');
                link.href = mp3Url;
                link.download = '文字转语音.mp3';
                link.click();
            };

            function float32ToInt16(buffer) { 
                let l = buffer.length;
                let buf = new Int16Array(l);

                while (l--) {
                    buf[l] = Math.min(1, buffer[l]) * 0x7FFF;
                }
                return buf;
            }

            synth.speak(utterance);
            utterance.onstart = function() {
                recorder.start();
            };
            utterance.onend = function() {
                recorder.stop();
            };
        });
    </script>
</body>
</html>