微信小程序语音识别和语音播放

进入小程序管理后台,菜单拉到最底下的设置,选择第三方设置,点击添加插件在这里插入图片描述

搜索微信同声传译插件,并添加
在这里插入图片描述

manifest.json源码视图中添加以下代码

"mp-weixin" : {
    "plugins": {
         "WechatSI": {
             "version": "0.3.5",
             "provider": "wx069ba97219f66d99"
         }
    }
}

语音识别以及语音播放demo注意:当前功能只支持真机模式,微信开发者工具上无法调试

<template>
  <view class="container">
      <button @touchstart="streamRecord" @touchend="endStreamRecord" 
	  form-type="submit" type="primary" class="fc-white">语音识别</button>
      <view class="result">{{currentText}}</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
       currentText:"",
	   manager:null,
	   plugin:null,
    };
  },
  onLoad() {
      // 同声传译
      this.plugin = requirePlugin("WechatSI")
      this.manager = this.plugin.getRecordRecognitionManager()
      // 语音播放
      this.innerAudioContext = wx.createInnerAudioContext()
      this.initRecord()
  },
  methods: {
      streamRecord(){
          console.log('=======开始====')
          this.manager.start({
              lang: 'zh_CN',
	  })
      },
      endStreamRecord(){
          console.log('=======结束====')
          this.manager.stop()
      },
      initRecord(){
         //有新的识别内容返回,则会调用此事件
         this.manager.onRecognize = (res) => {
	     this.currentText = res.result
         }
         // 识别结束事件
         this.manager.onStop = (res) => {
	     console.log('识别结束事件',res);
             const text = res.result
             if(text == '') {
                console.log('没有说话');
	  	return
             }
             this.currentText = text
             this.playstart(this.currentText)
         }
      },
      // 语音播报
      playstart(text){
	  const _this = this
	  _this.plugin.textToSpeech({
              lang:"zh_CN",
              content:text,
              success:(res)=>{
		  console.log('语音合成成功', res.filename)
		  _this.innerAudioContext.src = res.filename
		  // 开始播放
                  _this.innerAudioContext.play()
              },
              fail:(res)=>{
                  console.log('语音合成失败')
              }
	  })
      },
  },
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.record-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 200rpx;
  height: 100rpx;
  background-color: #0bb20c;
  border-radius: 50px;
  color: white;
  font-size: 32rpx;
  text-align: center;
}

.result {
  margin-top: 20px;
  font-size: 24rpx;
  text-align: center;
}
</style>
  • 12
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值