>  기사  >  위챗 애플릿  >  WeChat 애플릿에서 녹음 기능 및 오디오 재생을 호출하는 방법에 대한 자세한 그래픽 설명

WeChat 애플릿에서 녹음 기능 및 오디오 재생을 호출하는 방법에 대한 자세한 그래픽 설명

高洛峰
高洛峰원래의
2017-03-20 15:25:5920945검색

기존 규칙, 먼저 사진 몇 장.

1. 명확하게 보려면 처음에 오디오 목록이 로드되지 않습니다.

WeChat 애플릿에서 녹음 기능 및 오디오 재생을 호출하는 방법에 대한 자세한 그래픽 설명

2. 녹음 버튼을 길게 누르면 가운데 마이크가 나오는데

사실은 js를 사용해 디스플레이를 제어하는 ​​것입니다. 여기서는 말할 것도 없습니다. 녹화란 무엇입니까? WeChat의 녹화 API를 사용하면 녹화 시간이 너무 짧을 경우 녹화가 실패하므로 처리해야 합니다. . 녹음 시간 제한은 위챗 보이스 60초와 동일합니다.

WeChat 애플릿에서 녹음 기능 및 오디오 재생을 호출하는 방법에 대한 자세한 그래픽 설명

3.녹음 완료 후 목록을 로드했습니다. 아래 사진은 위챗에 저장된 파일에서 얻은 목록 정보입니다.

여기에 있는 파일은 단순한 오디오가 아닐 수도 있습니다. . 다음 경로는 모두 wx:file//store_...

Tencent/에서는 micromsg/wxafiles/wx..../ 디렉토리에서도 찾아볼 수 있습니다. >

포맷 후 시간은 B이며, KB로의 변환은 다음과 같습니다.

전화번호부는 다음과 같습니다. 현재는 이유를 알 수 없습니다.WeChat 애플릿에서 녹음 기능 및 오디오 재생을 호출하는 방법에 대한 자세한 그래픽 설명

다음은 파일의 전체 이름입니다.WeChat 애플릿에서 녹음 기능 및 오디오 재생을 호출하는 방법에 대한 자세한 그래픽 설명

1. 임시 파일 두 번째로 미니 프로그램에 들어가면 정상적으로 사용할 수 없습니다.

2.savedFilePath: 영구 저장되는 파일의 경로는 100M만 제공된다는 점이 좋습니다. 최대한 빨리 하시려면 백그라운드에 올려주세요.

4. 녹음된 오디오를 재생하세요.

WeChat 애플릿에서 녹음 기능 및 오디오 재생을 호출하는 방법에 대한 자세한 그래픽 설명목소리를 들으시려면 해당 항목을 클릭하세요. 혼자서 겁먹지 마세요.

코드:

WeChat 애플릿에서 녹음 기능 및 오디오 재생을 호출하는 방법에 대한 자세한 그래픽 설명1.index.wxml

<!--index.wxml-->
<scroll-view>
        <view wx:if="{{voices}}" class="common-list" style="margin-bottom:120rpx;">
                <block  wx:for="{{voices}}">
                <view class="board">
                <view class="cell"  >
                <view class="cell-bd" data-key="{{item.filePath}}" bindtap="gotoPlay" > 
                <view  class="date">存储路径:{{item.filePath}}</view>
                <view  class="date" >存储时间:{{item.createTime}}</view>
                <view  class="date">音频大小:{{item.size}}KB</view>
                </view>  

                </view>
                </view>
                </block>
        </view>
</scroll-view>

<view  wx:if="{{isSpeaking}}"  class="speak-style">
        <image class="sound-style" src="../../images/voice_icon_speech_sound_1.png" ></image>
        <image wx:if="{{j==2}}" class="sound-style" src="../../images/voice_icon_speech_sound_2.png" ></image>
        <image wx:if="{{j==3}}" class="sound-style" src="../../images/voice_icon_speech_sound_3.png" ></image>
        <image wx:if="{{j==4}}" class="sound-style" src="../../images/voice_icon_speech_sound_4.png" ></image>
        <image wx:if="{{j==5}}"class="sound-style" src="../../images/voice_icon_speech_sound_5.png" ></image>
</view>
<view class="record-style">
        <button class="btn-style" bindtouchstart="touchdown" bindtouchend="touchup">按住 录音</button>
</view>

2.index.wxss

/**index.wxss**/  
.speak-style{  
    position: relative;  
    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: 0;  
    left: 0;  
    height: 120rpx;  
    width: 100%;  
}  
.btn-style{  
  margin-left: 30rpx;  
  margin-right: 30rpx;  
}  
  
.sound-style{  
  position: absolute;  
  width: 74rpx;  
  height:150rpx;  
  margin-top: 45rpx;  
  margin-left: 83rpx;  
}  
  
  
.board {  
  overflow: hidden;  
  border-bottom: 2rpx solid #26A5FF;    
}  
/*列布局*/  
.cell{  
    display: flex;  
    margin: 20rpx;  
}  
.cell-hd{  
    margin-left: 10rpx;  
    color: #885A38;  
}  
.cell .cell-bd{  
    flex:1;  
    position: relative;  
     
}  
/**只显示一行*/  
.date{  
    font-size: 30rpx;  
    text-overflow: ellipsis;   
    white-space:nowrap;  
    overflow:hidden;   
}

3 .index.js

//index.js  
//获取应用实例  
var app = getApp()  
Page({  
  data: {  
    j: 1,//帧动画初始图片  
    isSpeaking: false,//是否正在说话  
    voices: [],//音频数组  
  },  
  onLoad: function () {  
  },  
  //手指按下  
  touchdown: function () {  
    console.log("手指按下了...")  
    console.log("new date : " + new Date)  
    var _this = this;  
    speaking.call(this);  
    this.setData({  
      isSpeaking: true  
    })  
    //开始录音  
    wx.startRecord({  
      success: function (res) {  
        //临时路径,下次进入小程序时无法正常使用  
        var tempFilePath = res.tempFilePath  
        console.log("tempFilePath: " + tempFilePath)  
        //持久保存  
        wx.saveFile({  
          tempFilePath: tempFilePath,  
          success: function (res) {  
            //持久路径  
            //本地文件存储的大小限制为 100M  
            var savedFilePath = res.savedFilePath  
            console.log("savedFilePath: " + savedFilePath)  
          }  
        })  
        wx.showToast({  
          title: &#39;恭喜!录音成功&#39;,  
          icon: &#39;success&#39;,  
          duration: 1000  
        })  
        //获取录音音频列表  
        wx.getSavedFileList({  
          success: function (res) {  
            var voices = [];  
            for (var i = 0; i < res.fileList.length; i++) {  
              //格式化时间  
              var createTime = new Date(res.fileList[i].createTime)  
              //将音频大小B转为KB  
              var size = (res.fileList[i].size / 1024).toFixed(2);  
              var voice = { filePath: res.fileList[i].filePath, createTime: createTime, size: size };  
              console.log("文件路径: " + res.fileList[i].filePath)  
              console.log("文件时间: " + createTime)  
              console.log("文件大小: " + size)  
              voices = voices.concat(voice);  
            }  
            _this.setData({  
              voices: voices  
            })  
          }  
        })  
      },  
      fail: function (res) {  
        //录音失败  
        wx.showModal({  
          title: &#39;提示&#39;,  
          content: &#39;录音的姿势不对!&#39;,  
          showCancel: false,  
          success: function (res) {  
            if (res.confirm) {  
              console.log(&#39;用户点击确定&#39;)  
              return  
            }  
          }  
        })  
      }  
    })  
  },  
  //手指抬起  
  touchup: function () {  
    console.log("手指抬起了...")  
    this.setData({  
      isSpeaking: false,  
    })  
    clearInterval(this.timer)  
    wx.stopRecord()  
  },  
  //点击播放录音  
  gotoPlay: function (e) {  
    var filePath = e.currentTarget.dataset.key;  
    //点击开始播放  
    wx.showToast({  
      title: &#39;开始播放&#39;,  
      icon: &#39;success&#39;,  
      duration: 1000  
    })  
    wx.playVoice({  
      filePath: filePath,  
      success: function () {  
        wx.showToast({  
          title: &#39;播放结束&#39;,  
          icon: &#39;success&#39;,  
          duration: 1000  
        })  
      }  
    })  
  }  
})  
//麦克风帧动画  
function speaking() {  
  var _this = this;  
  //话筒帧动画  
  var i = 1;  
  this.timer = setInterval(function () {  
    i++;  
    i = i % 5;  
    _this.setData({  
      j: i  
    })  
  }, 200);  
}

위의 구현을 통해 미니 프로그램에서 즐겁게 녹음하고 재생할 수 있다는 것을 배웠나요?

참고:


1. 녹음된 오디오는 기본적으로 로컬 임시 경로에 저장됩니다. 애플릿은 두 번째 입력 시 정상적으로 사용할 수 없습니다. .영구적으로 저장할 수 있지만 로컬 파일 크기 제한은 100M이므로 백그라운드에 업로드하는 것이 가장 좋습니다.

2. 녹음 시간이 너무 짧으면 안 됩니다. 60초 후에 녹음이 자동으로 중지됩니다.

3. 오디오 재생은 동시에 여러 오디오를 재생할 수 없습니다. 문서를 참조하세요. WeChat 애플릿

위 내용은 WeChat 애플릿에서 녹음 기능 및 오디오 재생을 호출하는 방법에 대한 자세한 그래픽 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.