需要实现的功能是:
输入一段文字,由小程序读出来
步骤如下:
一、小程序添加 “微信同声传译” 插件
添加插件步骤看这篇博===》如何添加插件并配置
二、代码编写
index.wxml里代码:
<!--index.wxml-->
<view class="container">
<textarea class="text"></textarea>
<view class="btn">
<button bindtap="start"> 开始 </button>
<button bindtap="end"> 结束 </button>
</view>
</view>
index.wxss里代码
/**index.wxss**/
.container{
width: 100%;
height: 600rpx;
background: silver;
}
.text{
width: 500rpx;
background: honeydew;
}
.btn{
width: 500rpx;
display: flex;
justify-content: space-between;
margin-top: 50rpx;
}
.btn button{
width: 200rpx;
}
index.js里代码分开展示:
① 先引入插件
//引入插件:微信同声传译
const plugin = requirePlugin('WechatSI');
② onReady里添加如下代码
onReady: function () {
//创建内部 audio 上下文 InnerAudioContext 对象。
this.innerAudioContext = wx.createInnerAudioContext();
this.innerAudioContext.onError(function (res) {
console.log(res);
wx.showToast({
title: '语音播放失败',
icon: 'none',
})
})
}
③ 文字转语音部分代码
// 文字转语音
start: function (e) {
var that = this;
var content = this.data.content;
plugin.textToSpeech({
lang: "zh_CN",
tts: true,
// content: content,
content: "速度:" + speed + " 力量:" + strength,
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: function (e) {
if (this.data.src == '') {
console.log("暂无语音");
return;
}
this.innerAudioContext.src = this.data.src //设置音频地址
this.innerAudioContext.play(); //播放音频
},
// 结束语音
end: function (e) {
this.innerAudioContext.pause(); //暂停音频
},
index.js所有代码:
//index.js
//获取应用实例
const app = getApp()
//引入插件:微信同声传译
const plugin = requirePlugin('WechatSI');
Page({
data: {
src: '', //路径
},
// 文字转语音
start: function (e) {
var that = this;
var content = this.data.content;
plugin.textToSpeech({
lang: "zh_CN",
tts: true,
// content: content,
content: "速度:" + speed + " 力量:" + strength,
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: function (e) {
if (this.data.src == '') {
console.log("暂无语音");
return;
}
this.innerAudioContext.src = this.data.src //设置音频地址
this.innerAudioContext.play(); //播放音频
},
// 结束语音
end: function (e) {
this.innerAudioContext.pause(); //暂停音频
},
onReady: function () {
//创建内部 audio 上下文 InnerAudioContext 对象。
this.innerAudioContext = wx.createInnerAudioContext();
this.innerAudioContext.onError(function (res) {
console.log(res);
wx.showToast({
title: '语音播放失败',
icon: 'none',
})
})
}
})
Github 已上传:路径