Enregistreur de développement d'applets WeChat, lecture audio, animation

小云云
Libérer: 2018-03-17 13:14:26
original
3014 Les gens l'ont consulté

Cet article partage principalement avec vous le développement d'applets WeChat pour les enregistreurs, la lecture audio et les animations. J'espère qu'il pourra aider tout le monde.

1. Afin d'entrer et de voir clairement, la liste audio n'est pas chargée au début. Il suffit d'avancer le code.


2. Lorsque vous appuyez et maintenez le bouton d'enregistrement, un microphone apparaîtra. Le microphone au milieu est une animation de cadre

En fait, il utilise js pour contrôler les images. Afficher masquer. Il n'y a rien à dire ici, c'est l'enregistrement. Après l'API d'enregistrement de WeChat, si la durée d'enregistrement est trop courte, l'enregistrement échouera. vous devez toujours vous en occuper en cas d'échec. La limite de temps d'enregistrement et la voix WeChat sont identiques, 60 secondes.


3. Je ne charge la liste qu'une fois l'enregistrement terminé.

L'image ci-dessous représente les informations de liste obtenues à partir des fichiers stockés dans WeChat. Il existe des chemins de stockage et de création. les temps et la taille des fichiers.

Les fichiers ici peuvent Ce n'est pas seulement de l'audio, je ne porte aucun jugement ici. Les chemins ci-dessous sont tous wx:file//store_...

Je l'ai également recherché dans Tencent/micromsg/wxafiles/ Vous pouvez le trouver dans le répertoire wx..../

Le temps est après le formatage. La taille du fichier est B et la conversion en Ko est la suivante.


Le répertoire du téléphone mobile est le suivant. Mais il ne peut pas être lu après l'avoir ouvert. La raison est actuellement inconnue.


<.>


Ce qui suit est le nom complet du fichier.

1.tempFilePath : Le fichier temporaire après enregistrement. Il ne peut pas être utilisé normalement après avoir entré l'applet pour la deuxième fois.

2.savedFilePath : le chemin du fichier persistant est à noter que WeChat ne dispose que de 100 M d'espace de stockage. . Il est préférable de le télécharger sur le backend dès que possible


4. Jouez l'audio enregistré

Cliquez sur l'élément pour entendre votre voix.

Code :

1.index.wxml

2.index.wxss
<!--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>
Copier après la connexion
Copier après la connexion


3 .index.js
/**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;   
}
Copier après la connexion
Copier après la connexion


Remarque :

//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);  
}
Copier après la connexion

1. L'audio enregistré est stocké localement temporairement par chemin par défaut. Le mini-programme ne peut pas être utilisé normalement lorsque vous le saisissez pour la deuxième fois. Il peut être enregistré de manière permanente, mais la limite de taille du fichier local est de 100 Mo. Il est préférable de le télécharger en arrière-plan.

2.录音的时间不能太短.否则会失败;也不能超过60秒.到了60秒会自动停止录音.

3.音频播放不能同时播放多个音频.看文档.微信小程序 播放音频文档

1.为了进来看得清楚.刚开始没有加载音频列表.代码往前挪一挪即可.


2.按住 录音按钮的时候会出现麦克风.中间的麦克风是个帧动画.

其实就是用js控制图片显示隐藏.没啥好说的.这里值得说一说的是录音.微信的录音API后,如果录音时间太短,会录音失败.所以fail的时候还是需要处理一下.录音时间的限制和微信语音是一样的.60秒.


3.我在录音完成后才加载列表.

下图就是从微信存储的文件里获取到的列表信息.有储存路径,创建时间,文件大小.

这里的文件可能不只是音频.这里我没做判断.下面的路径都是wx:file//store_...

我也去找了下.在Tencent/micromsg/wxafiles/wx..../这一级目录就能找到了.

时间是格式化之后的.文件大小是B,转成KB如下.


手机目录如下.但是打开之后播放不了.目前原因不明.



下面是文件全名称.

1.tempFilePath : 录音之后的临时文件.第二次进入小程序就不能正常使用了.

2.savedFilePath :持久保存的文件路径.值得注意的是微信只给100M的储存空间.还是尽早上传到后台吧.



4.播放录音音频.

点击item就能听到你的声音了.别被自己吓住.哈哈.




上代码:

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>
Copier après la connexion
Copier après la connexion

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;   
}
Copier après la connexion
Copier après la connexion


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);  
}
Copier après la connexion



注意:

1. L'audio enregistré est stocké dans un chemin temporaire local par défaut. L'applet ne peut pas être utilisée normalement la deuxième fois qu'elle est saisie, mais la limite de taille du fichier local est de 100 Mo. Il est préférable de le télécharger en arrière-plan.

2. La durée d'enregistrement ne peut pas être trop courte, sinon elle ne peut pas dépasser 60 secondes. .

3. La lecture audio ne peut pas lire plusieurs audios en même temps. Consultez la documentation. L'applet WeChat lit les documents audio

Recommandations associées :

.

Exemple de développement de menu déroulant de simulation d'applet WeChat

Comment implémenter la boîte contextuelle dans le développement d'applets WeChat

Méthode détaillée de téléchargement de fichiers après enregistrement dans l'applet WeChat

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!