• 小程序 wx.getRecorderManager 录音 to 语音识别


    微信扫小程序码看调用效果(自然语言理解小助手)

    小程序码小 二维码小

    欢迎转载,请保留原文链接:http://www.happycxz.com/m/?p=125

    这次主要是把我的api更新了一下,支持微信小程序新的录音接口,录出来的是mp3格式。顺便更新一下我的微信小程序“遥知之”,用上新录音接口 wx.getRecorderManager 。

    这里只贴上关键代码:

    //获取应用实例 
    var app = getApp()
    
    var UTIL = require('../../utils/util.js');
    var GUID = require('../../utils/GUID.js');
    var NLI = require('../../utils/NLI.js');
    
    const appkey = require('../../config').appkey
    const appsecret = require('../../config').appsecret
    
    //微信小程序新录音接口,录出来的是aac或者mp3,这里要录成mp3
    const mp3Recorder = wx.getRecorderManager()
    const mp3RecoderOptions = {
      duration: 60000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'mp3',
      //frameSize: 50
    }
    
    //弹幕定时器
    var timer;
    
    var pageSelf = undefined;
    
    var doommList = [];
    class Doomm {
      constructor() {
    	this.text = UTIL.getRandomItem(app.globalData.corpus);
    	this.top = Math.ceil(Math.random() * 40);
    	this.time = Math.ceil(Math.random() * 8 + 6);
    	this.color = getRandomColor();
    	this.display = true;
    	let that = this;
    	setTimeout(function () {
    	  doommList.splice(doommList.indexOf(that), 1);
    	  doommList.push(new Doomm());
    
    	  pageSelf.setData({
    		doommData: doommList
    	  })
    	}, this.time * 1000)
      }
    }
    function getRandomColor() {
      let rgb = []
      for (let i = 0; i < 3; ++i) {
    	let color = Math.floor(Math.random() * 256).toString(16)
    	color = color.length == 1 ? '0' + color : color
    	rgb.push(color)
      }
      return '#' + rgb.join('')
    }
    
    Page({
      data: {
    	j: 1,//帧动画初始图片 
    	isSpeaking: false,//是否正在说话
    	outputTxt : "", //输出识别结果
    
    	doommData: []
      },
    
      initDoomm: function () {
    	doommList.push(new Doomm());
    	doommList.push(new Doomm());
    	doommList.push(new Doomm());
    	this.setData({
    	  doommData: doommList
    	})
      },
    
      onLoad: function () {
    	pageSelf = this;
    	this.initDoomm();
    
    	//onLoad中为录音接口注册两个回调函数,主要是onStop,拿到录音mp3文件的文件名(不用在意文件后辍是.dat还是.mp3,后辍不决定音频格式)
    	mp3Recorder.onStart(() => {
    	  UTIL.log('mp3Recorder.onStart()...')
    	})
    	mp3Recorder.onStop((res) => {
    	  UTIL.log('mp3Recorder.onStop() ' + res)
    	  const { tempFilePath } = res
    	  var urls = "https://api.happycxz.com/wxapp/mp32asr";
    	  UTIL.log('mp3Recorder.onStop() tempFilePath:' + tempFilePath)
    	  processFileUploadForAsr(urls, tempFilePath, this);
    	})
      },
    
      /////////////////////////////////////////////////////////////// 以下是调用新接口实现的录音,录出来的是 mp3
      touchdown: function () {
      //touchdown_mp3: function () {
    	UTIL.log("mp3Recorder.start with" + mp3RecoderOptions)
    	var _this = this;
    	speaking.call(this);
    	this.setData({
    	  isSpeaking: true
    	})
    	mp3Recorder.start(mp3RecoderOptions);
      },
      touchup: function () {
      //touchup_mp3: function () {
    	UTIL.log("mp3Recorder.stop")
    	this.setData({
    	  isSpeaking: false,
    	})
    	mp3Recorder.stop();
      },
    
    
      //切换到老版本
      turnToOld: function () {
    	wx.navigateTo({
    	  url: '../index/index',
    	})
      },
    
      /////////////////////////////////////////////////////////////// 以下是调用老接口实现的录音,录出来的是 silk_v3
      //手指按下 
      touchdown_silk: function () {
      //touchdown: function () {
    	UTIL.log("手指按下了... new date : " + new Date)
    	var _this = this;
    	speaking.call(this);
    	this.setData({
    	  isSpeaking: true
    	})
    	//开始录音 
    	wx.startRecord({
    	  success: function (res) {
    		//临时路径,下次进入小程序时无法正常使用
    		var tempFilePath = res.tempFilePath;
    		UTIL.log('record SUCCESS file path:' + tempFilePath)
    		_this.setData({
    		  recordPath: tempFilePath
    		});
    	  },
    	  fail: function (res) {
    		//录音失败 
    		wx.showModal({
    		  title: '提示',
    		  content: '录音的姿势不对!',
    		  showCancel: false,
    		  success: function (res) {
    			if (res.confirm) {
    			  UTIL.log('用户点击确定')
    			  return
    			}
    		  }
    		})
    	  }
    	})
      },
      //手指抬起 
      touchup_silk: function () {
      //touchup: function () {
    	UTIL.log("手指抬起了...")
    	this.setData({
    	  isSpeaking: false,
    	})
    	clearInterval(this.timer)
    	wx.stopRecord()
    
    	var _this = this
    	setTimeout(function () {
    	  var urls = "https://api.happycxz.com/wxapp/silk2asr/";
    	  UTIL.log(_this.data.recordPath);
    	  processFileUploadForAsr(urls, _this.data.recordPath, _this);
    	}, 1000)
      },
    
    
    })
    
    //上传录音文件到 api.happycxz.com 接口,处理语音识别和语义,结果输出到界面
    function processFileUploadForAsr(urls, filePath, _this) {
      wx.uploadFile({
    	url: urls,
    	filePath: filePath,
    	name: 'file',
    	formData: { "appKey": appkey, "appSecret": appsecret, "userId": UTIL.getUserUnique() },
    	header: { 'content-type': 'multipart/form-data' },
    	success: function (res) {
    	  UTIL.log('res.data:' + res.data);
    
    	  var nliResult = getNliFromResult(res.data);
    	  UTIL.log('nliResult:' + nliResult);
    	  var stt = getSttFromResult(res.data);
    	  UTIL.log('stt:' + stt);
    
    	  var sentenceResult;
    	  try {
    		sentenceResult = NLI.getSentenceFromNliResult(nliResult);
    	  } catch (e) {
    		UTIL.log('touchup() 错误' + e.message + '发生在' + e.lineNumber + '行');
    		sentenceResult = '没明白你说的,换个话题?'
    	  }
    
    	  var lastOutput = "==>语音识别结果:
    " + stt + "
    
    ==>语义处理结果:
    " + sentenceResult;
    	  _this.setData({
    		outputTxt: lastOutput,
    	  });
    	  wx.hideToast();
    	},
    	fail: function (res) {
    	  UTIL.log(res);
    	  wx.showModal({
    		title: '提示',
    		content: "网络请求失败,请确保网络是否正常",
    		showCancel: false,
    		success: function (res) {
    		}
    	  });
    	  wx.hideToast();
    	}
      });
    }
    
    function getNliFromResult(res_data) {
      var res_data_json = JSON.parse(res_data);
      var res_data_result_json = JSON.parse(res_data_json.result);
      return res_data_result_json.nli;
    }
    
    function getSttFromResult(res_data) {
      var res_data_json = JSON.parse(res_data);
      var res_data_result_json = JSON.parse(res_data_json.result);
      return res_data_result_json.asr.result;
    }
    
    //麦克风帧动画 
    function speaking() {
      var _this = this;
      //话筒帧动画 
      var i = 1;
      this.timer = setInterval(function () {
    	i++;
    	i = i % 5;
    	_this.setData({
    	  j: i
    	})
      }, 200);
    }
    

    主要调用API的地方是:processFileUploadForAsr()。
    代码中保留了 touchdown_silk 和 touchup_silk 是调用小程序提供的老录音接口录silk的,可以参考,换老接口也是可以用的。

    与“遥知之”相关的博客文章主要在我的CSDN博客中:
    http://blog.csdn.net/happycxz/article/details/78024986

    该API服务搭建全过程解析及源码分享贴:
    http://blog.csdn.net/happycxz/article/details/78016299

    这次的代码更新,托管在github上,感兴趣的可以关注:
    api服务器端github项目
    小程序端github项目

  • 相关阅读:
    JAVA软件开发职责
    Redis主从复制配置
    VirtualBox安装Ubuntu教程
    分段锁——ConcurrentHashMap
    阻塞队列BlockingQueue用法
    阻塞队列--LinkedBlockingQueue
    MySQL百万级数据库优化方案
    获取主机的对外ip
    联通沃云开启80端口
    Nginx 正则匹配
  • 原文地址:https://www.cnblogs.com/happycxz/p/7810396.html
Copyright © 2020-2023  润新知