您当前的位置: 首页 > 知识百科 > 微信小程序语音上传怎么弄

微信小程序语音上传怎么弄

时间:2023-07-01 14:05 阅读数:13 人阅读 分类:知识百科

  大家愿意使用小程序除了小程序特点之一就是方便之外,还因为小程序功能的完备和强大。最近很多人开始研究微信小程序语音上传要怎么弄,接下来小编为大家讲述一下,希望能够帮助到大家。

  1、微信小程序语音上传概述

  微信小程序语音上传其实就是通过小程序wx.startRecord()和wx.stopRecord()接口,使用小程序录音功能并上传silk录音文件至服务器,通过ffmpeg将silk录音文件转成wav录音文件,再通过百度语音识别 REST API 获取语音识别后的结果。

  2、微信小程序语音上传操作代码

  录音和语音文件上传

  //index.js

  //开始录音。当主动调用wx.stopRecord,

  //或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。

  //当用户离开小程序时,此接口无法调用。

  wx.startRecord({

  success: function (res) {

  console.log('录音成功' + JSON.stringify(res));

  that.setData({

  voiceButtonName: '语音识别',

  voicePlayButtonName: '开始播放',

  tempFilePath: res.tempFilePath

  })

  //上传语音文件至服务器

  wx.uploadFile({

  url: '你的域名/upload',

  filePath: res.tempFilePath,

  name: 'file',

  // header: {}, // 设置请求的 header

  formData: {

  'msg': 'voice'

  }, // HTTP 请求中其他额外的 form data

  success: function (res) {

  // success

  console.log('begin');

  console.log(res.data);

  var json = JSON.parse(res.data);

  console.log(json.msg);

  var jsonMsg = JSON.parse(json.msg);

  console.log(jsonMsg.result);

  wx.navigateTo({

  url: '../voicePage/voicePage?voiceData=' + jsonMsg.result.join('')

  })

  },

  fail: function (err) {

  // fail

  console.log(err);

  },

  complete: function () {

  // complete

  }

  })

  },

  fail: function (res) {

  //录音失败

  that.setData({

  voiceButtonName: '语音识别'

  })

  console.log('录音失败' + JSON.stringify(res));

  }

  })

  setTimeout(function () {

  //结束录音

  wx.stopRecord()

  }, 60000)

  node.js服务端接收语音文件代码

  //upload.js

  //使用koa-multer这个组件

  var multer = require('koa-multer');

  var router = require('koa-router')();

  var path = require('path');

  //存储文件至path.resolve('./voice-file')路径

  var upload = multer({ dest: path.resolve('./voice-file')});

  router.post('/', upload.single('file'), async function (ctx, next) {

  //这是就文件的具体信息

  console.log(ctx.req.file);

  });

  silk文件转wav文件

  我使用的是silk-v3-decoder将silk文件转wav文件

  silk-v3-decoder 使用方法

  //upload.js

  var exec = require('child_process').exec;

  function silkToWav(file){

  return new Promise(function (resolve, reject) {

  exec('sh converter.sh ' + file + ' wav', function(err,stdout,stderr){

  if(err) {

  resolve({

  result : false,

  msg : stderr

  });

  } else {

  //var data = JSON.parse(stdout);

  console.log(stdout);

  console.log(stderr);

  //console.log(err);

  resolve({

  result : true,

  msg : ''

  });

  }

  });

  });

  }

  微信小程序语音上传怎么弄大家看完以上资料都知道了吗?其实就是通过小程序wx.startRecord()和wx.stopRecord()接口录音并上传silk录音文件至微信小程序商店服务器,很简单的,快试试吧。

  

  微信小程序语音组件的使用方法

  小程序语音对话开发实例

  微信小程序语音聊天功能怎么实现?