js实现文字转语音

32 阅读1分钟

为什么有这个需求

中午睡醒,突发奇想,那些听小说是怎么做的,然后百度了一下,鼓捣了一个多小时,有了这篇文章

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文字转语音</title>
    <script src="./test99999999.js"></script>
</head>

<body>
    <button id="btn">test</button>
    <button id="pause">pause</button>
    <button id="resume">resume</button>

    <script>
        const synth = speechSynthesis;

        const btn = document.getElementById('btn');
        btn.addEventListener('click', () => {
            speak()
        });

        const pause = document.getElementById('pause');
        pause.addEventListener('click', () => {
            synth.pause();
        });

        const resume = document.getElementById('resume');
        resume.addEventListener('click', () => {
            synth.resume();
        });


        let sIndex = 0; eIndex = 100; len = book.length
        const speak = () => {
            const text = book.slice(sIndex, eIndex > len ? len : eIndex)
            const utterThis = new SpeechSynthesisUtterance(text);
            // const voices = synth.getVoices();
            // console.log(voices)
            utterThis.rate = 3;//语速
            utterThis.addEventListener('start', () => { console.log('start') })
            utterThis.addEventListener('end', () => {
                console.log('end1')
                if (eIndex >= len) return
                sIndex = eIndex
                eIndex += 100
                speak()
            })
            synth.speak(utterThis);
        }

    </script>
</body>

</html>

这个代码在chrome 136 版本运行成功,其他的没试过,这个是我当前使用的版本

这个api初步使用起来还是比较简单,嘿嘿

目前使用的声音是系统自带的,那种特别的声音暂时还在探索

参考文章

1、MDN

2、JS实现将文字转换为语音并自动播放

3、语音包