小程序集成录音与播放API

方式一(最简单)

<button bindtap='start'>开始录音</button>  
<button bindtap='play'>播放录音</button>  
<button bindtap='stop'>停止录音</button>

js

start: function () {
  //开始录音  
  wx.startRecord({
    success: function (e) {
      //录音文件 根据业务逻辑操作
      voice = e.tempFilePath
    }
  })
},
play: function () {
  //播放声音文件  
  wx.playVoice({
    filePath: voice
  })
},
 
stop: function () {
  //结束录音  
  wx.stopRecord();
}

方式二(全面)

<view class="container">
  <view class="voice-add" wx:if="{{state == 1}}">
    <view>{{voiceTimer || ''}}</view>
    <view class="operation-btn">
      <button bindtap='voiceIntroduced' data-type="{{clickFlag?'1':'3'}}">{{clickFlag?'开始录音':'停止录音'}}</button>
      <button bindtap='voiceIntroduced' data-type="2">播放录音</button>
    </view>
  </view>
  <view class="voice-edit" wx:if="{{state == 2}}">
    <view class="flex flex-column align-items-center">
      <image bindtap='voiceIntroduced' data-type="{{!playState?'5':'6'}}" src="{{!playState?'../../images/icon-play.png':'../../images/icon-stopPlay.png'}}"></image>
      <text>点击播放试听</text>
    </view>
    <view>
      <button bindtap='voiceIntroduced' data-type="4">重录</button>
    </view>
  </view>
</view>
const recorderManager = wx.getRecorderManager(),
  innerAudioContext = wx.createInnerAudioContext();
var voice = "",timer;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    playVoice: false, //录音状态
    state: '', //跳转类型 1-编辑界面 2-重录界面
    playState: false, //播放状态
    voiceTimer: '', //显示录音时间
    clickFlag: true, //点击状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    this.setData({
      state: options.state
    })
    //获取之前保存后的录音文件
    voice = options.voiceUrl;
    console.log("录音",options, options.voiceUrl)
  },

  //录音操作
  voiceIntroduced:function(event){
    var type = event.currentTarget.dataset.type,
        self = this,time = 0;
    switch (type) {
      case '1': //开始录音
        self.setData({playVoice: true});
        innerAudioContext.pause();
        const options = {
          duration: 600000, //指定录音的时长,单位 ms,最大为10分钟(600000),默认为1分钟(60000)
          sampleRate: 16000, //采样率
          numberOfChannels: 1, //录音通道数
          encodeBitRate: 96000, //编码码率
          format: 'mp3', //音频格式,有效值 aac/mp3
          frameSize: 50, //指定帧大小,单位 KB
         }
         
        //开始录音
        recorderManager.start(options);
        recorderManager.onStart(() => {
          // wx.showToast({
          //   title: "开始录音..",
          //   icon: 'none'
          // });
          self.setData({clickFlag: false});
          timer = setInterval(()=>{
            time++
            self.setData({
              voiceTimer: self.timeToFormat(time)
            })
            console.log("计时器",time)
          },1000)
          console.log('。。。开始录音。。。')
        });
        //错误回调
        recorderManager.onError((res) => {
          console.log(res);
        })
         
        break;
      case '2': //播放录音
        if(!self.data.playVoice && voice){
          wx.showToast({
            title: "播放中..",
            icon: 'none',
          });
          innerAudioContext.src = voice;
          //在ios下静音时播放没有声音,默认为true,改为false
          innerAudioContext.obeyMuteSwitch = false
          innerAudioContext.play();
          //播放结束
          innerAudioContext.onEnded(() => {
            innerAudioContext.stop()
          })
        }else if(!voice && !self.data.playVoice){
          wx.showToast({
            title: "没找到录音文件,快去录音吧!",
            icon: 'none'
          });
        }else{
          wx.showToast({
            title: "录音还未停止!",
            icon: 'none',
            duration: 2000
          });
        }
        console.log("播放",voice,"状态",self.data.playVoice)
        break;
      case '3': //停止录音
        if(self.data.playVoice){
          recorderManager.stop();
          recorderManager.onStop((res) => {
            console.log('停止录音', res.tempFilePath,"时长",res.duration)
            self.setData({clickFlag: true, voiceTimer: ''});
            clearInterval(timer);
            self.setData({playVoice: false});
            const {
              tempFilePath,
              duration
            } = res;
            let voiceSeconds = parseInt(duration / 1000); 
            console.log("录音时长",voiceSeconds,"本地录音文件",tempFilePath)
            //上传录音
            wx.uploadFile({
              url: '' //后台的api链接
              filePath: tempFilePath,
              name: "file", 
              header: {
                "Content-Type": "multipart/form-data"
              },
              success: function (res) {
                var fileData = JSON.parse(res.data);
                //上传后返回的网络路径
                voice = fileData.data[0].file;
                //根据业务逻辑操作
               
              },
              fail: function (res) {
                console.log("录音保存失败");
              }
            })
          })
        }
        if(voice){ //暂停播放
          innerAudioContext.pause();
        }
        break;
      case '4': //重录
        self.setData({state:1})
        break;
      case '5': //试听
        if(!voice){
          wx.showToast({
            title: "没找到录音文件,快去录音吧!",
            icon: 'none',
          });
          return
        }
        self.setData({playState:true})
        innerAudioContext.src = voice;
        innerAudioContext.obeyMuteSwitch = false
        innerAudioContext.play();
        //播放结束
        innerAudioContext.onEnded(() => {
          innerAudioContext.stop()
        })
        console.log("试听",voice)
        break;
      case '6': //暂停试听
        innerAudioContext.pause();
        self.setData({playState:false});
        console.log("暂停试听")
        break;
    }
  },
  //时长秒数转换
  timeToFormat: function(times){
    var result = '00:00:00';
    var hour,minute,second
    if (times > 0) {
      hour = Math.floor(times / 3600);
      if (hour < 10) {
        hour = "0"+hour;
      }
      minute = Math.floor((times - 3600 * hour) / 60);
      if (minute < 10) {
        minute = "0"+minute;
      }

      second = Math.floor((times - 3600 * hour - 60 * minute) % 60);
      if (second < 10) {
        second = "0"+second;
      }
      result = hour+':'+minute+':'+second;
    }
    return result;  
  },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值