首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JavaScript 朗读文本,播放声音

JavaScript 朗读文本,播放声音

作者头像
iVampireSP.com
发布2020-11-19 14:08:38
2.9K0
发布2020-11-19 14:08:38
举报

前言

由于网页设计大赛的事,想要搞点高级货,但是这周五就要交稿了,所以折腾一点没那么难的却很酷炫的功能。

设定文本

你可以预先设定待会要被播放的文本。

fetch('https://v1.hitokoto.cn') .then(response => response.json()) .then(data => { const hitokoto = document.getElementById('textarea-1') hitokoto.href = 'https://hitokoto.cn/?uuid=' + data.uuid hitokoto.innerText = data.hitokoto }) .catch(console.error)

天使坠落之时…

使用浏览器合成声音

这里一个除了IE以外的主流浏览器可以使用的功能

var sound = window.speechSynthesis; // 定义局部变量
var read_text = new SpeechSynthesisUtterance(text); // 实例化
sound.speak(read_text); // 朗读

其中将text改成你所需要朗读的文本,或者取变量里面的值。

使用JQuery 做个示例

var sound = window.speechSynthesis;
var read_text = new SpeechSynthesisUtterance($("#textarea").text());
sound.speak(read_text);

function read_1() { var sound = window.speechSynthesis; var read_text = new SpeechSynthesisUtterance($('#textarea-1').text()); sound.speak(read_text); }

阅读

但是这样你会发现一个问题:播放时浏览器并不会提示,甚至可能无法方便的暂停。 但是也不是没有好处的,因为这不需要白嫖API接口,就是兼容性有些差。

使用百度TTS播放自定义文本语音

所以我们可以白嫖百度TTS接口啊(滑稽)

audio = document.createElement('audio'); // 声明audio全局变量并创建元素
source = document.createElement('source'); // 声明source全局变量并创建元素
source.type = "audio/mpeg"; // source类型
source.src = 'https://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=8&text=' + $('#textarea').text(); // 拼接URL并读取要朗读的内容,设定src地址
source.autoplay = "autoplay"; // 自动播放
source.controls = "controls"; // 显示控件(其实没必要)
audio.appendChild(source); // 作为source的父元素
audio.play(); // 播放
使用jQuery做个示例
audio = document.createElement('audio');
source = document.createElement('source');
source.type = "audio/mpeg";
source.src = 'https://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=8&text=' + $('#textarea').text();
source.autoplay = "autoplay";
audio.appendChild(source);
audio.play();

function read_2() { audio = document.createElement('audio'); source = document.createElement('source'); source.type = "audio/mpeg"; source.src = 'https://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=8&text=' + $('#textarea-1').text(); source.autoplay = "autoplay"; audio.appendChild(source); audio.play(); }阅读

优点:使用audio标签,可控音频播放。 缺点:需要联网。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-11-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
    • 设定文本
      • 使用浏览器合成声音
        • 使用JQuery 做个示例
      • 使用百度TTS播放自定义文本语音
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档