1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 【微信小程序】语音播报 文字转语音 使用《微信同声传译插件》

【微信小程序】语音播报 文字转语音 使用《微信同声传译插件》

时间:2019-06-23 07:13:52

相关推荐

【微信小程序】语音播报 文字转语音 使用《微信同声传译插件》

需要实现的功能是:

输入一段文字,由小程序读出来

步骤如下:

一、小程序添加 “微信同声传译” 插件

添加插件步骤看这篇博===》如何添加插件并配置

二、代码编写

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;plugin.textToSpeech({lang: "zh_CN",tts: true,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: 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;plugin.textToSpeech({lang: "zh_CN",tts: true,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: 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 已上传:路径

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。