1、使用微信小程序的同声传译功能
小程序平台-设置-第三方设置-插件管理-新增同声传译插件
小程序app.json文件配置
"plugins": {
"WechatSI": {
"version": "0.3.5",
"provider": "wx069ba97219f66d99"
}
},
小程序中使用
.xml
<view class="action-box">
<view class="action-btn" wx:if="{{!isPlaying}}" bind:tap="textToSpeech">播放</view>
<view class="action-btn" wx:else bind:tap="pauseSpeech">暂停</view>
</view>
.js
var plugin = requirePlugin("WechatSI")
data: {
audioContext: null,
isPlaying: false,
text:'这是一个微信小程序文字转语音的功能'
}
textToSpeech(e) {
let name = e.currentTarget.dataset.name
let that = this
if (this.audioContext) {
this.audioContext.destroy()
}
plugin.textToSpeech({
lang: "zh_CN",
tts: true,
content: name,
success: function (res) {
that.audioContext = wx.createInnerAudioContext();
that.audioContext.src = res.filename;
that.audioContext.play();
that.setData({
isPlaying: true
})
that.audioContext.onEnded(() => {
that.setData({
isPlaying: false
})
})
},
fail: function (res) {
console.log("fail", res)
}
})
},
pauseSpeech() {
console.log(111,this.data.isPlaying,this.audioContext);
if (!this.data.isPlaying) return;
this.setData({
isPlaying: false
})
this.audioContext && this.audioContext.pause();
},