小程序录音|语音 示例2

标签:   

wxml

<!--index.wxml--> 
<view  wx:if="{{isSpeaking}}"  class="speak-style">  
    <image class="sound-style" src="../../images/icon/ly.gif" ></image>
 </view>   

 <view class="record-style">  
 <button class="btn-style" bindtouchstart="touchdown" bindtouchend="touchup">按住 录音</button> 
 <button bindtap="play">播放</button> 
 </view>  
wxss

/**index.wxss**/  
.speak-style{  
    position: fixed;  
    z-index: 999;
    left: 250rpx;
    height: 240rpx;  
    width: 240rpx;  
    border-radius: 20rpx;  
    margin: 50% auto;  
    background: #26A5FF;  
}  
.item-style{  
    margin-top: 30rpx;  
    margin-bottom: 30rpx;  
}  
.text-style{  
    text-align: center;    
}  
.record-style{  
    position: fixed;  
    bottom: 100rpx;  
    left: 0;  
    height: 120rpx;  
    width: 100%;  
}  
.btn-style{  
  margin-left: 30rpx;  
  margin-right: 30rpx;  
}  
.sound-style{  
  position: absolute;  
  width: 150rpx;  
  height:150rpx;  
  margin-top: 45rpx;  
  margin-left: 45rpx;  
}  
js

//index.js
//获取应用实例
const app = getApp()
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
var tempFilePath;
Page({
  data: {

  },

  //手指按下  
  touchdown: function () {
    console.log("手指按下了...")

    var _this = this;
    this.setData({
      isSpeaking: true
    })

    const options = {
      duration: 10000,//指定录音的时长,单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式,有效值 aac/mp3
      frameSize: 50,//指定帧大小,单位 KB
    }

    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')      
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
  },
  //手指抬起  
  touchup: function () {
    console.log("手指抬起了...")
    this.setData({
      isSpeaking: false
    })
    recorderManager.stop();
    recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      console.log('停止录音', res.tempFilePath)
      const { tempFilePath } = res
    })
  },
  //播放声音
  play: function () {
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
        innerAudioContext.onEnded   ((res) => {
          wx.showToast({
            title: '播放结束',
            icon: 'success',
            duration: 1000
          })

        })

      })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })

  },
  onLoad: function () {

  },
})
小程序录音及播放完整代码 示例1. 原文出自[忆云竹] 转载请保留原文链接: http://eyunzhu.com/683.html


发表评论 登录

目前评论:1

  • avatar 菇凉 回复 2019-02-22 23:27:04

    mark标记