1.想要实现微信的语音播放需要在微信公众号后台下载微信同声传译插件,可以去微信服务平台搜索此插件并下载,指定对应的小程序号就行了。
2.下载完在 微信小程序后台--设置--第三方设置-- 插件管理-- 进入 微信同声传译详情 复制插件AppID 到 app.json 进行配置:
app.json:
"plugins": {
"WechatSI": {
"version": "0.3.5",
"provider": "wx069ba97219f66d99"
}
}
wxml:
js
//引入插件:微信同声传译
const plugin = requirePlugin('WechatSI');
//创建内部 audio 上下文 InnerAudioContext 对象。
const innerAudioContext = wx.createInnerAudioContext();
Page({
data: {
content: '',//内容
src:'', //
},
onReady(e) {
innerAudioContext.onError(function (res) {
console.log(res);
wx.showToast({
title: '语音播放失败',
icon: 'none',
})
})
},
// 手动输入内容
content(e) {
// console.log(e);
this.setData({
content: e.detail.value,
})
},
// 文字转语音
start (e) {
var that = this;
var content = this.data.content;
plugin.textToSpeech({
lang: "zh_CN",
tts: true,
content: content,
success: function (res) {
console.log(res);
console.log("succ tts", res.filename);
that.setData({
src: res.filename
})
that.yuyinPlay();
},
fail: function (res) {
console.log("fail tts", res)
}
})
},
//播放语音
yuyinPlay(e) {
if (this.data.src == '') {
console.log(暂无语音);
return;
}
// console.log("正在播放");
innerAudioContext.autoplay = true
innerAudioContext.src = this.data.src //设置音频地址
innerAudioContext.play(); //播放音频
},
// 结束语音
end (e) {
innerAudioContext.pause();//暂停音频
},
})
wxss:
.wrap {
margin-top:300rpx;
height: 200px;
}
.content {
border: 1px solid #ccc;
margin: 0 auto;
padding: 10rpx 10rpx 70rpx;
}
.btn {
width: 100px;
height: 70rpx;
border: 1px solid #eee;
background: #fff;
color: #606267;
margin-left: 100px;
}
.box{
width: 300px;
/* border: 1px solid red; */
}
.start{
margin-left: 40px;
}
PS:长文本处理,由于语音播放文本限制为:1000字节。需要进行分段处理
// 点击朗读
readlongText() {
//同声传译一次最多1000字节,长文本按300字进行截断,然后按照朗读速度估算300字的时间,延迟下一次读取,正常300字/1分17秒
let arrText = this.data.content.replace(/\r/g, ",").replace(/\n/g, ",").replace(/\s+/g, ",").replace(/#/g, ",");
console.log(arrText, arrText.length) //获取全文+总数字
// arrText= arrText.replace(/[`:_.~!@#$%^&*() \+ =<>?"{}|, \/ ;' \\ [ \] ·~!@#¥%……&*()—— \+ ={}|《》?:“”【】、;‘’,。、]/g,
// ''); //去除标点符号
if (arrText.length < 300) {
// 总数字小于300,直接转为语音
this.read(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字的段落
console.log(text)
setTimeout(() => {
this.read(text)
}, time * 1000 * i); //每隔1分17秒读一段
}
}
},
// 文字转语音
read(content) {
var that = this;
plugin.textToSpeech({
lang: "zh_CN",
tts: true,
content: content,
success: function (res) {
// console.log(res);
// console.log("succ tts", res.filename);
that.setData({
src: res.filename
})
that.yuyinPlay();
},
fail: function (res) {
console.log("fail tts", res)
}
})
},
//播放语音
yuyinPlay(e) {
if (this.data.src == '') {
console.log(暂无语音);
return;
}
// console.log("正在播放");
innerAudioContext.autoplay = true
innerAudioContext.src = this.data.src //设置音频地址
innerAudioContext.play(); //播放音频
},
// 结束语音
end(e) {
innerAudioContext.pause(); //暂停音频
},
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)