Mini program voice search function, voice recognition translates into text for search

1. The wepy framework is used.

<view class="{
   
   {recordState?'speakInfoActive':'speakInfo'}}" catchtouchstart="touchStart" catchtouchend="touchEnd">按住说话</view>

2.js part

const plugin = requirePlugin('WechatSI');
const manager = plugin.getRecordRecognitionManager();
export default class send extends wepy.page {
	config = {
		navigationBarTitleText: '搜索'
	};
	data = {
  	recordState: false, //录音状态
    }
    onLoad(option) {
		this.initRecord();
    }
    }
initRecord(){
  manager.stop() 
    const that = this;
    // 有新的识别内容返回,则会调用此事件
    manager.onRecognize = function (res) {
      console.log(res)
    }
    manager.onStart = function (res) {
      console.log("成功开始录音识别", res)
    }
    // 识别错误
    manager.onError = function (res) {
			wx.showToast({
                    title: `请等待识别完成!`,
                    icon: 'none',
                    duration: 2000
      })
      console.error("error msg", res)
    }
    //识别结束
    manager.onStop = function (res) {
      if (res.result == '') {
        wx.showModal({
          title: '提示',
          content: '听不清楚,请重新说一遍!',
          showCancel: false,
          success: function (res) {}
        })
        return;
      }
			that.searchValue = res.result.slice(0, -1)
			that.searchFun()
			that.$apply()
    }
  }
  //开始
  touchStart(e){
    const that = this;
    that.recordState=true
		that.$apply()
    manager.start({ lang: 'zh_CN'})
  }
  //结束
  touchEnd(e){
    const that = this;
    that.recordState=false
		that.$apply()
    manager.stop();
  }
}

3. Style

	.speakInfo{
		margin: 1rpx auto;
		margin-top: 20rpx;
		width: 140rpx;
		height: 60rpx;
		line-height: 60rpx;
		border: 0.5px solid #999;
		border-radius: 30rpx;
		font-size: 26rpx;
		color: #999999;
		text-align: center;
	}
	.speakInfoActive{
		margin: 1rpx auto;
		margin-top: 20rpx;
		width: 140rpx;
		height: 60rpx;
		line-height: 60rpx;
		border: 0.5px solid #3a85fa;
		border-radius: 30rpx;
		font-size: 26rpx;
		color:#ffffff;
		text-align: center;
		background: #3a85fa;
	}

Guess you like

Origin blog.csdn.net/qq_44890362/article/details/133317678