文章目录
概要
需要用户一开始进入小程序的某个页面就进行语音播报
解决方案
使用微信小程序插件“微信同声传译”可以达到该功能
具体实现:
1. 微信公众平台=>设置=>第三方设置=>插件管理=>添加插件=>‘微信同音传译’=>添加(目前暂不支持个人开发者使用):
2、引入小程序插件:
2.1 复制插件AppID
2.2 打开项目中的manifest.json=>源码视图=>添加如下代码:
3、具体代码实现:
<template>
<view class="content">
<button @click="openVoice">播放语音</button>
</view>
</template>
<script>
const plugin = requirePlugin('WechatSI');
const innerAudioContext = wx.createInnerAudioContext();
export default {
data() {
return {
title: 'Hello'
};
},
onLoad() {
this.openVoice();
},
onReady() {
innerAudioContext.onError(function (res) {
wx.showToast({
title: '语音播放失败',
icon: 'none'
});
});
},
methods: {
openVoice() {
let _this = this;
console.log(plugin);
plugin.textToSpeech({
lang: 'zh_CN',
tts: true,
content: '支付宝成功收款200万元',
success: function (res) {
console.log('succ tts', res.filename);
_this.yuyinPlay(res.filename)
},
fail: function (res) {
console.log('fail tts', res);
},
complete: function (res) {
console.log('complete tts', res);
}
});
},
yuyinPlay(src) {
if (src == '') {
return;
}
innerAudioContext.autoplay = true;
innerAudioContext.src = src; //设置音频地址
innerAudioContext.play(); //播放音频
}
}
};
</script>
4、如果播报的内容比较多的话,可以采取分段播放处理:
<template>
<view class="content">
<button @click="handleMoreText('支付宝成功收款200万元')">播放语音</button>
</view>
</template>
<script>
const plugin = requirePlugin('WechatSI');
const innerAudioContext = wx.createInnerAudioContext();
export default {
data() {
return {
title: 'Hello'
};
},
onLoad() {
this.handleMoreText('支付宝成功收款200万元');
},
onReady() {
innerAudioContext.onError(function (res) {
wx.showToast({
title: '语音播放失败',
icon: 'none'
});
});
},
methods: {
/**
* @description: 处理文本 同声传译一次最多1000字节,长文本按300字进行截断,然后按照朗读速度估算300字的时间,延迟下一次读取,正常300字/1分17秒
* @param {*} content
* @return {*}
*/
handleMoreText(content) {
let arrText = content.replace(/\r/g, ',').replace(/\n/g, ',').replace(/\s+/g, ',').replace(/#/g, ','); // 去除标点符号
console.log(arrText, arrText.length); // 获取全文+总数字
if (arrText.length < 300) {
// 总数字小于300,直接转为语音
this.openVoice(arrText);
} else {
// 总数字大于300,拆分成多个段落
const num = Math.ceil(arrText.length / 300);
const time = 75;
for (let i = 0; i < num; i++) {
const text = arrText.substr(0 + i * 300, 300); // 全文分成多个300字的段落
setTimeout(() => {
this.openVoice(text);
}, time * 1000 * i); // 每隔1分17秒读一段
}
}
},
openVoice(content) {
let _this = this;
console.log(plugin);
plugin.textToSpeech({
lang: 'zh_CN',
tts: true,
content,
success: function (res) {
console.log('succ tts', res.filename);
_this.yuyinPlay(res.filename);
},
fail: function (res) {
console.log('fail tts', res);
},
complete: function (res) {
console.log('complete tts', res);
}
});
},
yuyinPlay(src) {
if (!src) return;
innerAudioContext.autoplay = true;
innerAudioContext.src = src; // 设置音频地址
innerAudioContext.play(); // 播放音频
}
}
};
</script>