您所在的位置:首页 / 知识分享

wx小程序录音并上传到后端保存[后端PHP]

2020.07.30

1333

wngpng

wxml文件:

<view class="container">
  <view class="audio_ctl">
    <button bindtouchstart="handleRecordStart" bindtouchend="handleRecordEnd">长按录音</button>
    <button bindtap="handlePlayVoice">播放</button>
    <button bindtap="handleUploadVoice">上传</button>
    <view class="uploaded">
      <view>已上传文件url: </view>
      <text>{{uploaded_url}}</text>
    </view>
    <audio controls src="https://fanyi.baidu.com/gettts?lan=cte&text=%e4%bd%a0%e5%a5%bd%ef%bc%8c%e7%82%b9%e5%8e%bb%e4%bd%93%e8%82%b2%e9%a6%86&spd=5&source=web" />
  </view>
</view>

js文件:

//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    record_tmpfile: '',     // 最近一次录音的临时文件路径;
    record_ms: '',          // 录音的毫秒数
    uploaded_url: '',       // 已上传文件的路径;
    userInfo: {}
  },

  // 录音功能: 
  handleRecordStart: function(e) {
    const that = this;
    const timeStart = Date.now();
    wx.startRecord({
      success: function (res) {
        console.log('record success res: ', res);
        var tempFilePath = res.tempFilePath
        that.setData({
          record_tmpfile: tempFilePath,
          record_ms: Date.now() - timeStart,
        });
      },
      fail: function (res) {
        //录音失败
        console.log('record fail res: ', res);
        wx.stopRecord();
        if(res.errMsg.indexOf('auth') >= 0) {
          wx.showModal({
            title: '无法录音',
            content: '您已经拒绝访问麦克风,无法使用录音功能,如需使用,请删除此小程序,并重新搜索打开',
            showCancel: false,
          });
        } else {
          wx.showToast({
            title: '未知错误',
          })
        }
      }
    })
    setTimeout(function () {
      //结束录音  
      wx.stopRecord()
    }, 60000);
  },

  // 停止录音: 
  handleRecordEnd: function(e) {
    wx.stopRecord()
  },
  
  // 播放录音: 
  handlePlayVoice: function() {
    console.log('start play voice');
    wx.playVoice({
      filePath: this.data.record_tmpfile,
    })
  },
  // 上传录音
  handleUploadVoice: function() {
    const { record_tmpfile, record_ms } = this.data;
    wx.showLoading({ title: '上传中' });
    const that = this;
    wx.uploadFile({
      url: app.api_url + '/upload/uploadfile.php', 
      filePath: record_tmpfile,
      name: 'file',
      formData: {
        audio_ms: record_ms,
      },
      success: function (res) {
        wx.hideLoading();
        var data = res.data
        console.log('upload_res: ', res);
        const data2 = JSON.parse(res.data);
        console.log('upload res data2: ', data2);
        //do something
        let toastTitle = '上传成功';
        if (data2.c != 0) {
          toastTitle = data2.m;
        } else {
          that.setData({ uploaded_url: data2.d});
        }
        setTimeout(function() {
          wx.showToast({ title: toastTitle });
        }, 500);
      },
      fail: function(res) {
        wx.hideLoading();
      }
    })
  }
})

PHP后端接收保存:

// 封装返回json数据格式方法
function json_response($c=0, $m='', $d='') {
    $data = array(
        'code'     =>  $c,
        'msg'     =>  $m,
        'data'     =>  $d
    );
    return json_encode($data);
}

// 接收小程序传递参数(即:小程序录音市场参数等)
$params = json_decode(file_get_contents("php://input"), true);
$audio_ms = $params['audio_ms'];

// 接收小程序上传录音文件
if(!array_key_exists('file', $_FILES)) {
    return json_response(-1,'未传入文件',$readPath);
}

// 获取临时文件路径并构造新文件名称
$file = $_FILES['file']['tmp_name'];
$randFileName = 'weapp_audio_' . md5(uniqid("", true));

// 将临时文件保存到服务器中
$savePath = '/data/wwwroot/www.h5tpl.com/web/uploads/xcxvoice/' . $randFileName . '.silk';
file_put_contents($savePath, file_get_contents($file));

//获取服务器中保存的录音文件路径并返回到小程序客户端中
$readPath = 'https://www.h5tpl.com/uploads/xcxvoice/' . $randFileName . '.silk';
return json_response(200,'上传成功',$readPath);

相关新闻

SEO & SEM

2015.11.03

2729

安装VirtualBox6.1.34后报错Kernel driver not installed (rc=-1908) 解决方法

2023.03.10

968

macOS Monterey12.3.1安装VirtualBox6.1.34后报错Kernel driver not installed (rc=-1908) 解决方法

Go 每日一练之类型断言

2020.08.05

1243

Go 类型断言广泛用于interfer{}类型转为其他类型(经常出现在map类型中),另外只有initerface类型才可以进行类型断言。