糖尿病康复,内容丰富有趣,生活中的好帮手!
糖尿病康复 > js语音播报android浏览器 JS 简单调用百度TTS接口实现语音朗读

js语音播报android浏览器 JS 简单调用百度TTS接口实现语音朗读

时间:2023-02-25 20:29:05

相关推荐

js语音播报android浏览器 JS 简单调用百度TTS接口实现语音朗读

TTS简介

TTS是Text To Speech的缩写,即“从文本到语音”,是人机对话的一部分,让机器能够说话。网页作为世界之窗,自然是向所有人开放的,所以也就包括视力不好的人群了,而网页语音化并不是什么新技术,HTML语义化在某种层次上也是为了让网页语音化更好的实现。

正文

简单实现语音朗读,要说多简单,直接用别人的接口算不算简单?

我们要做的就是借用百度TTS接口,通过audio标签进行朗读。实现核心如下:

需要一个audio标签,包括其中的source标签,对audio标签不了解的可以去W3C HTML5音频教程看看

在audio的子标签source中设置src,具体内容为:src="/text2audio?lan=zh&ie=UTF-8&spd=8&text="+content (content是要朗读的内容)

参数:{

lan:语言,

ie:编码,

spd:语速(1-9),

text:要朗读的内容

}

audio标签可自定义controls,autoplay等标签特性,实现控制(可选)

audio标签主要通过js添加,HTML代码如下

JS代码

var content = "hello"

var s = docuement.querySelector("#tts_source")

s.src = s.src + content

s.parentNode.load()

由于修改了audio的source标签,需要对audio进行刷新重加载,故用s.parentNode.load()方法

总结

该方法灵活性不太好,想要朗读网页内容需要获取不同的标签,而且内容文本不能过大(由于写入的文本是通过Get方式传给百度接口的,传送的文本数量受Get URL 请求的限制,不同的浏览器限制大小不尽相同,且中文占字符数较多)

附文

网页添加以下脚本可实现文本框输入值后进行朗读

//百度TTS地址

var url = "/text2audio/text2audio?lan=zh&ie=UTF-8&spd=8&text="

//添加audio标签

var f = document.createDocumentFragment()

var audio = document.createElement("audio")

audio.controls="controls"

audio.autoplay="autoplay"

var source = document.createElement("source")

source.id = "tts_source"

source.type="audio/mpeg"

source.src= url

audio.appendChild(source)

f.appendChild(audio)

document.body.appendChild(f)

//添加输入框和按钮

var f1 = document.createDocumentFragment()

var form = document.createElement("form")

var textArea = document.createElement("textarea")

textArea.rows="25"

textArea.cols="50"

textArea.name="content"

var startBtn = document.createElement("input")

startBtn.type = "button"

startBtn.value = "Start"

startBtn.onclick = function(){

content = document.forms[0]["content"].value

var sorce = document.querySelector("#tts_source")

source.src = url + content

sorce.parentNode.load()

}

form.appendChild(textArea)

form.appendChild(startBtn)

f1.appendChild(form)

document.body.appendChild(f1)

如果觉得《js语音播报android浏览器 JS 简单调用百度TTS接口实现语音朗读》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。