? ? 語音播報(bào)的實(shí)現(xiàn)的方法有很多種,我這里介紹集中不引用百度、阿里或者迅飛的API的實(shí)現(xiàn)方式。
一、采用new SpeechSynthesisUtterance的方式
廢話不多說直接上代碼
data() {
return {
utterThis:null,
}
},
//方法使用
this.utterThis = new SpeechSynthesisUtterance('');
this.utterThis.pitch = 1; // 音高
this.utterThis.rate = 1; // 語速
this.utterThis.volume = 1; // 音量
this.utterThis.lang = 'zh-CN';
this.utterThis.text = "要播報(bào)的文本內(nèi)容";
window.speechSynthesis.speak(this.utterThis); //開始朗讀
方法的結(jié)束事件
this.utterThis.onend = () => { //結(jié)束事件
window.speechSynthesis.cancel() //注銷合成方法
}
二、采用speak-tts插件的方式
1、安裝speak-tts
npm install speak-tts
2.使用
import Speech from 'speak-tts' //引入
初始化調(diào)用
this.speechInit();
speechInit(){
this.speech = new Speech();
this.speech.setLanguage('zh-CN');
this.speech.init().then(()=>{
console.log('語音播報(bào)初始化完成')
})
},
this.speech.speak({text:item.newsContent}).then(()=>{
this.speech.cancel(); //播放結(jié)束后調(diào)用
})
三、微信小程序可以采用微信提供的插件
1、添加插件?
2.由于我用的是uni-app,所以manifest.json添加配置
"mp-weixin" : {
"appid" : "這個(gè)是小程序的appid",
"setting" : {
"urlCheck" : true,
"es6" : true,
"minified" : true,
"postcss" : false
},
"optimization" : {
"subPackages" : true
},
"usingComponents" : true,
"plugins" : {
"WechatSI" : {
"version" : "0.3.5",
"provider" : "填寫剛才申請(qǐng)的appid"
}
}
},
3.項(xiàng)目中使用
//條件編譯 引入插件
// #ifdef MP-WEIXIN
var plugin = requirePlugin("WechatSI")
let manager = plugin.getRecordRecognitionManager()
// #endif
// #ifdef MP-WEIXIN
let _this=this
plugin.textToSpeech({
lang: "zh_CN",
tts: true,
content: playword,
success: function(res) {
_this.src = res.filename //這個(gè)就是生成成功的音頻
_this.smallRoutine(item,playword,index);
},
fail: function(res) {}
})
// #endif
//然后利用uni.createInnerAudioContext() 進(jìn)行播放
//如果不會(huì)使用 請(qǐng)移步 https://uniapp.dcloud.net.cn/api/media/audio-context.html#createinneraudiocontext
this.innerAudioContext = uni.createInnerAudioContext()
this.innerAudioContext.pause();
this.innerAudioContext.volume = 1
this.innerAudioContext.src = this.src
this.innerAudioContext.play()
this.innerAudioContext.onEnded(()=>{
//監(jiān)聽結(jié)束事件 做自己的處理邏輯
})
?4.如果合成音頻不能播放可進(jìn)行開發(fā)文檔狀態(tài)碼查詢 。(有時(shí)候可能文字過長(zhǎng)無法合成報(bào)錯(cuò),我這里可以提供一種思路,文字截取一段一段的)?
比如:(全部代碼就不貼了)文章來源:http://www.zghlxwxcb.cn/news/detail-594453.html
let strlength =this.contentTxt.slice().length;
if(strlength>200){
this.playAllNum=Math.ceil(strlength / 200);
playword = this.contentTxt.slice(0,200)
}else{
this.playAllNum=1;
playword =this.contentTxt
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-594453.html
到了這里,關(guān)于uni-app/vue 文字轉(zhuǎn)語音朗讀(附小程序語音識(shí)別和朗讀)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!