uniapp WeChat applet: RecorderManager recording DEMO

uniapp WeChat applet: RecorderManager recording DEMO

Introduction

Use RecorderManagerfor recording. and related basic operations. (Get file information, upload files)
This picture contains the server program used for uploading and testing in Demo. After downloading, use the decompression tool to open it.
This picture contains the server program used for uploading test in Demo upload.exe, after downloading, use the decompression tool to open it.
The upload interface is as shown in the code: http://127.0.0.1:8999/upload
the uploaded file is saved in upload.exethe directory where it is located.

index.view

For a single-file demo, create an empty project and copy and paste it.

<template>
	<view class="content">
		<view class="title">{
   
   {title}}</view>
		<view>
			<button :disabled="!btnStatus[0]" @click="startRecord">开始录音</button>
			<button :disabled="!btnStatus[1]" @click="endRecord">停止录音</button>
			<button :disabled="!btnStatus[2]" @click="playVoice">播放录音</button>
			<button :disabled="!btnStatus[3]" @click="upload">上传录音</button>
		</view>
	</view>
</template>

<script>
	const recorderManager = uni.getRecorderManager();			// 获取全局唯一的录音管理器
	const innerAudioContext = uni.createInnerAudioContext();	// 创建并返回内部 audio 上下文 innerAudioContext 对象。
	const fileSystemManager = uni.getFileSystemManager();		// 获取全局唯一的文件管理器
	
	innerAudioContext.autoplay = true;
	
	export default {
      
      
		data() {
      
      
			return {
      
      
				title: 'uniapp 微信小程序:录音DEMO',
				// 录音文件的信息
				voiceData: {
      
      
					filePath: '',
					fileSize: 0,
					duration : 0,
					size: 0,
					digest: ''
				},
				btnStatus: [true , false, false, false]
			}
		},
		onLoad() {
      
      
			let that = this;
			// 录音结束
			recorderManager.onStop(function (res) {
      
      
				console.log(`录音完成:${ 
        JSON.stringify(res)}`); 
				// 录音完成:{"tempFilePath":"http://tmp/f4XillI6c9vm8652ed79724d0ef901d35c490534061c.durationTime=2724.aac","fileSize":24344,"duration":2724}
				that.voiceData = {
      
       fileSize: res.fileSize,duration : res.duration };
				// 拿临时文件信息
				console.log(`临时文件信息:`); 
				that.getFileInfo(res.tempFilePath);
				// 保存临时文件到本地。此接口会移动临时文件,因此调用成功后,tempFilePath 将不可用。
				uni.getFileSystemManager().saveFile({
      
      
					tempFilePath: res.tempFilePath,
					success(res){
      
      
						console.log( `保存文件成功: ${ 
        JSON.stringify(res)}` );
						// 保存文件成功: {"errMsg":"saveFile:ok","savedFilePath":"http://store/tAqiVVvp35eBa041b8ab5d91cd7eac88402ed9b4fa6d.durationTime=2079.aac"}
						that.voiceData.filePath = res.savedFilePath;
						// 保存完成,获取文件信息
						console.log(`已保存的文件信息:`); 
						that.getFileInfo(res.savedFilePath,res=>{
      
      
							that.voiceData.size = res.size;
							that.voiceData.digest = res.digest;
						});
					},
					fail(err){
      
      
						console.error( `保存文件失败: ${ 
        JSON.stringify(err)}` );
					},
					complete(){
      
      
						console.log('保存文件: 擦屁股');
					}
				})
			});
		},
		methods: {
      
      
			startRecord() {
      
      
				console.log('开始录音');	
				recorderManager.start({
      
      
					duration: 60000,		// 录音持续时间最长60秒
					sampleRate: 8000,		// 采样率 8000 说话录音足够了
					numberOfChannels: 1		// 单声道
				});
				this.btnStatus = [0, 1, 0, 0];
			},
			endRecord() {
      
      
				console.log('录音结束');
				recorderManager.stop();
				this.btnStatus = [1, 0, 1, 1];
			},
			playVoice() {
      
      
				console.log('播放录音');
				if ( this.voiceData.filePath) {
      
      
					innerAudioContext.src = this.voiceData.filePath;
					innerAudioContext.play();
				}
			},
			upload(){
      
      
				console.log( `上传文件: ${ 
        JSON.stringify(this.voiceData)}`);
				// 上传文件: {
      
      
				// 	"fileSize":18588,"duration":2102,"size":13941,"digest":"902f377a3921f52dd1141c578974ad9a",
				// 	"filePath":"http://store/AZkfdB7PuHqp08e30b555ede419af0dc129ed30970b8.durationTime=2102.aac"
				// }
				let uploadTask = uni.uploadFile({
      
      
					url: 'http://127.0.0.1:8999/upload',
					filePath: this.voiceData.filePath,			// 要上传的文件的路径
					name: 'file',								// 表单 name,服务端按这个名接文件
					formData: this.voiceData,					// 额外的信息
					success(res){
      
      
						console.log( `上传成功: ${ 
        JSON.stringify(res)}` );
					},
					fail(err){
      
      
						console.error( `上传失败: ${ 
        JSON.stringify(err)}` );
					},
					complete(){
      
      
						console.log('上传文件: 擦屁股');
					}
				});
				
				uploadTask.onProgressUpdate((res) => {
      
      
					console.log('上传进度' + res.progress);
					console.log('已经上传的数据长度' + res.totalBytesSent);
					console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
					// 测试条件,取消上传任务。
					if (res.progress > 90) {
      
      
						uploadTask.abort();
					}
				});
			},
			// 获取该小程序下的 本地临时文件 或 本地缓存文件 信息
			getFileInfo(filePath, success){
      
      
				// 获取文件信息
				fileSystemManager.getFileInfo({
      
      
					filePath: filePath,
					success(res){
      
      
						if(typeof success === 'function'){
      
      
							success(res);
						}else{
      
      
							console.log( `获取文件信息成功: ${ 
        JSON.stringify(res)}` );
							console.log( `大小:${ 
        res.size / 1024 }K ` );
						}
					},
					fail(err){
      
      
						console.error( `获取文件信息失败: ${ 
        JSON.stringify(err)}` );
					},
					complete(){
      
      
						console.log( '获取文件信息: 擦屁股' );
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.content {
      
      
		height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		
		.title {
      
      
			margin: 30rpx 0;
			font-size: $uni-font-size-lg;
			font-weight: bold;
		}
	}
</style>

References

uni.getRecorderManager() obtains the globally unique recording manager
uni.createInnerAudioContext() creates and returns the inner audio context innerAudioContext object
uni.uploadFile(OBJECT) uploads local resources to the developer server

wx.getFileSystemManager() Gets the globally unique file manager. Base library 1.9.9 started to support.
FileSystemManager.getFileInfo(Object object) Get the local temporary file or local cache file information under the applet

Guess you like

Origin blog.csdn.net/jx520/article/details/132494112