用HTML5和JavaScript实现语音合成朗读 您所在的位置:网站首页 朗读当前页面所有文字 用HTML5和JavaScript实现语音合成朗读

用HTML5和JavaScript实现语音合成朗读

2024-07-11 09:08| 来源: 网络整理| 查看: 265

用HTML5和JavaScript实现语音合成朗读

win10环境下

先给出效果图,最后给出完整代码

完整代码如下:

网页版文字转语音朗读功能 article {margin: 0 auto;max-width: 800px;text-align: center;} textarea {max-width: 600px;width:100%;text-align: left;} button{border-radius: 3px;border: 1px solid #dddddd;height: 30px;width: 80px;cursor: pointer;} 请在下面文本框中输入要朗读的文本:

本网页版本语音合成播报支持Microsoft Edge等浏览器,不必连接网络。

选择播报语音:

开始 继续 暂停 清空文本 if(!('speechSynthesis' in window)) { throw alert("对不起,您的浏览器不支持") } var _play = document.querySelector("._play"), to_speak = window.speechSynthesis, dataName, voiceSelect = document.querySelector("#voiceSelect"), voices = []; function play() { myCheckFunc();//检查文本框是否为空 cancel(); // to_speak = new SpeechSynthesisUtterance(_play.value); //to_speak.rate = 1.4;// 设置播放语速,范围:0.1 - 10之间 var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length; i++) { if(voices[i].name === selectedOption) { to_speak.voice = voices[i]; } } window.speechSynthesis.speak(to_speak); } //暂停 function pause() { myCheckFunc();//检查文本框是否为空 window.speechSynthesis.pause(); } //继续播放 function resume() { myCheckFunc();//检查文本框是否为空 window.speechSynthesis.resume(); //继续 } //清除所有语音播报创建的队列 function cancel() { window.speechSynthesis.cancel(); } //清空文本框 function cls() { document.getElementById("texts").value=""; 清空文本框 } //检查文本框是否为空 function myCheckFunc() { let x; x = document.getElementById("texts").value; try { if (x === "") throw "文本框为空"; } catch (error) { alert( "提示" + error); } } //创建选择语言的select标签 function populateVoiceList() { voices = speechSynthesis.getVoices(); for(i = 0; i < voices.length; i++) { var option = document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textContent += ' -- DEFAULT'; } option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); voiceSelect.appendChild(option); } } setTimeout(function() { populateVoiceList(); }, 500) //

保存为文件名为 网页版文字转语音朗读.html,用浏览器打开后显示如上图,选择适当的播报语言,再单击“开始”按钮就开始播报了,你可以在文本框中输入要朗读的文字。

参考资料:https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis

HTML5 中使用浏览器进行语音合成以及使用免费语音合成进行朗读 https://blog.csdn.net/dengmengxin/article/details/88668634

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有