uni-app/vue 文字转语音朗读(附小程序语音识别和朗读)

    语音播报的实现的方法有很多种,我这里介绍集中不引用百度、阿里或者迅飞的API的实现方式。

一、采用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 =  "要播报的文本内容";
window.speechSynthesis.speak(this.utterThis); //开始朗读

方法的结束事件

this.utterThis.onend = () => {  //结束事件   
	window.speechSynthesis.cancel()   //注销合成方法
}

二、采用speak-tts插件的方式

1、安装speak-tts

npm install speak-tts

2.使用

import Speech from 'speak-tts'  //引入


初始化调用
this.speechInit();


speechInit(){
	this.speech = new Speech();
	this.speech.setLanguage('zh-CN');
	this.speech.init().then(()=>{
		console.log('语音播报初始化完成')
	})
},


this.speech.speak({text:item.newsContent}).then(()=>{
	this.speech.cancel(); //播放结束后调用
})

三、微信小程序可以采用微信提供的插件

1、添加插件 

2.由于我用的是uni-app,所以manifest.json添加配置

"mp-weixin" : {
        "appid" : "这个是小程序的appid",
        "setting" : {
            "urlCheck" : true,
            "es6" : true,
            "minified" : true,
            "postcss" : false
        },
        "optimization" : {
            "subPackages" : true
        },
        "usingComponents" : true,
        "plugins" : {
            "WechatSI" : {
                "version" : "0.3.5",
                "provider" : "填写刚才申请的appid"
            }
        }
    },

3.项目中使用

//条件编译  引入插件

// #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 //这个就是生成成功的音频
		_this.smallRoutine(item,playword,index);
	},
	fail: function(res) {}
})
// #endif


//然后利用uni.createInnerAudioContext() 进行播放
//如果不会使用  请移步 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(()=>{
	//监听结束事件  做自己的处理逻辑
})

 4.如果合成音频不能播放可进行开发文档状态码查询 。(有时候可能文字过长无法合成报错,我这里可以提供一种思路,文字截取一段一段的) 

比如:(全部代码就不贴了)

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
}

扫描二维码关注公众号,回复: 16430818 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_42717015/article/details/131435881