HTML5+JavaScript实现语音合成(文字转语音)

HTML5+JavaScript实现语音合成(文字转语音)

本文介绍用HTML5和JavaScript实现语音合成朗读(文字转语音)。

Web Speech API 有两个部分:SpeechSynthesis 语音合成(文本到语音 TTS)和 SpeechRecognition 语音识别(异步语音识别)。权威文档可见:

https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Speech_API

在此我们关注语音合成。

语音合成通过 SpeechSynthesis 接口进行访问,它提供了文字到语音(TTS)的能力,这使得程序能够读出它们的文字内容(通常使用设备默认的语音合成器)。

https://developer.mozilla.org/zh-CN/docs/Web/API/SpeechSynthesis

使用HTML5实现语音朗读功能相对简单,主要用到的是Web Speech API。这是一个非常强大的API,允许网页合成语音(Text-to-Speech, TTS)。

下面给出比较完善的例子,先看效果图:

源码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>语音朗读</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        #text-area {
            width: 100%;
            height: 300px;
        }
        #controls {
            margin-top: 10px;
        }
        #controls button {
            padding: 5px 10px;
            margin-right: 10px;
        }
        #options {
            margin-top: 20px;
        }
        #options label {
            display: inline-block;
            width: 100px;
        }
    </style>
</head>
<body>

<textarea id="text-area" placeholder="在这里输入文本..."></textarea>
<div id="controls">
    <button id="speak-button">朗读</button>
    <button id="pause-button" disabled>暂停</button>
    <button id="resume-button" disabled>继续</button>
    <button id="stop-button" disabled>停止</button>
</div>
<div id="options">
    <label for="voice-select">选择声音:</label>
    <select id="voice-select"></select>
    <br>
    <label for="lang">语言:</label>
    <select id="lang">
        <option value="zh-CN">中文</option>
        <option value="en-US">英文</option>
    </select>
    <br>
    <label for="rate">语速:</label>
    <input type="range" id="rate" min="0.1" max="3" value="1" step="0.1">
    <br>
    <label for="volume">音量:</label>
    <input type="range" id="volume" min="0" max="1" value="1" step="0.1">
    <br>
    <label for="pitch">音调:</label>
    <input type="range" id="pitch" min="0" max="2" value="1" step="0.1">
</div>

<script>
    const textArea = document.getElementById('text-area');
    const speakButton = document.getElementById('speak-button');
    const pauseButton = document.getElementById('pause-button');
    const resumeButton = document.getElementById('resume-button');
    const stopButton = document.getElementById('stop-button');
    const voiceSelect = document.getElementById('voice-select');
    const langSelect = document.getElementById('lang');
    const rateRange = document.getElementById('rate');
    const volumeRange = document.getElementById('volume');
    const pitchRange = document.getElementById('pitch');
    let voices = [];

    function populateVoices() {
        voices = speechSynthesis.getVoices();
        voiceSelect.innerHTML = '';
        voices.forEach(voice => {
            const option = document.createElement('option');
            option.textContent = voice.name + " (" + voice.lang + ")";
            option.value = voice.name;
            voiceSelect.appendChild(option);
        });
    }

    if (speechSynthesis.onvoiceschanged !== undefined) {
        speechSynthesis.onvoiceschanged = populateVoices;
    }

    const utterance = new SpeechSynthesisUtterance();
    let isSpeaking = false;
    let isPaused = false;

    speakButton.addEventListener('click', function() {
        if (isSpeaking) {
            window.speechSynthesis.pause();
            pauseButton.disabled = true;
            updateButtons();
            return;
        }
        window.speechSynthesis.cancel();
        utterance.text = textArea.value;
        utterance.voice = voices.find(voice => voice.name === voiceSelect.value);
        utterance.lang = langSelect.value;
        utterance.rate = rateRange.value;
        utterance.volume = volumeRange.value;
        utterance.pitch = pitchRange.value;
        window.speechSynthesis.speak(utterance);
        isSpeaking = true;
        updateButtons();
    });

    pauseButton.addEventListener('click', function() {
        if (!isSpeaking || isPaused) return;
        window.speechSynthesis.pause();
        isPaused = true;
        updateButtons();
    });

    resumeButton.addEventListener('click', function() {
        if (!isSpeaking || !isPaused) return;
        window.speechSynthesis.resume();
        isPaused = false;
        updateButtons();
    });
    stopButton.addEventListener('click', function() {
        if (!isSpeaking) return;
        window.speechSynthesis.cancel();
        isSpeaking = false;
        isPaused = false;
        updateButtons();
    });

    function updateButtons() {
        speakButton.disabled = isSpeaking && !isPaused;
        pauseButton.disabled = !isSpeaking || isPaused;
        resumeButton.disabled = !isSpeaking || !isPaused;
        stopButton.disabled = !isSpeaking;
    }

    // 当朗读结束时更新状态
    utterance.onend = function() {
        isSpeaking = false;
        updateButtons();
    };

    // 当朗读出错时更新状态
    utterance.onerror = function() {
        isSpeaking = false;
        updateButtons();
    };

    // 页面加载完成后立即尝试填充语音列表
    populateVoices();
    // 如果在页面加载时语音列表不可用,那么当它变得可用时填充语音列表
    if (speechSynthesis.onvoiceschanged !== undefined) {
        speechSynthesis.onvoiceschanged = populateVoices;
    }

    // 初始化时更新按钮状态
    updateButtons();

</script>  
  
</body>  
</html>

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:目的是使语音技术能在互联网更广泛的应用。每一个页面,只要加入一段javascript脚本就能使用,经过1个多月的努力,终于初步实现的功能,首先在数字报纸上使用:
HTML5通过Web Speech API提供了实现语音文字的功能。这个API可以在浏览器中使用,无需下载或安装插件。具体实现语音文字的步骤如下: 1. 在HTML页面中引入SpeechRecognition对象。使用以下代码: ``` window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; ``` 2. 创建SpeechRecognition实例,并进行必要的配置。使用以下代码: ``` const recognition = new SpeechRecognition(); recognition.lang = 'zh-CN'; // 设置语言为中文 recognition.continuous = true; // 设置为连续识别模式 ``` 3. 为SpeechRecognition对象添加事件监听器,以监听语音识别过程中的不同阶段。包括开始语音识别、结束语音识别、获得识别结果等。使用以下代码: ``` recognition.onstart = function() { // 开始语音识别 }; recognition.onresult = function(event) { // 获取语音识别结果。event.results包含了识别出的所有文本结果 const transcript = event.results[event.results.length - 1][0].transcript; // 将识别结果展示在页面中 document.getElementById('text').textContent = transcript; }; recognition.onend = function() { // 结束语音识别 }; recognition.onerror = function(event) { // 处理语音识别错误 }; ``` 4. 启动语音识别功能。使用以下代码: ``` recognition.start(); ``` 5. 最后,将语音识别结果换成文字,可以通过修改页面元素的textContent或者使用Ajax将结果发送到服务器进行处理。 上述步骤简要介绍了在HTML5中实现语音文字的过程。通过Web Speech API,开发者可以轻松实现语音识别功能,为用户提供更加智能和便利的交互体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学习&实践爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值