微信小程序录音+播放

<view class="weui-cell weui-cell_input">
		<view class="weui-cell__hd">
			<view class="weui-label">音频说明</view>
		</view>
		<view class="weui-cell__bd luyin">
			 <button bindtap="record" class="r"> 录音 </button>
			 <button bindtap="stop" class="s"> 结束 </button>
			 <button bindtap="play" class="p"> 试听 </button>
		</view>
	</view>
	
//css
.luyin{
	padding: 12rpx 0 10rpx 0;
}
.luyin button{
	width: 140rpx;padding: 0;
	display: inline-block;
	height: 65rpx;line-height: 65rpx;
	font-size: 26rpx;margin-right: 20rpx;
	background: #fff;
}
.luyin button.r{
	border:2px solid  #1489ff;
	color: #1489ff;
}
.luyin button.s{
	border:2px solid #000;
	color: #000;
}
.luyin button.p{
	border:2px solid  #00ce0d;
	color: #00ce0d;
}

//js
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
Page({
	data:{},
	//停止录制
	stop: function() {
		recorderManager.stop()
		recorderManager.onStop((res) => {
			console.log('recorder stop', res)
			const {
				tempFilePath
			} = res
			console.log(tempFilePath)
			this.tempFilePath = tempFilePath
		})
	},
	//播放声音
	play: function() {
		innerAudioContext.autoplay = true
		innerAudioContext.src = this.tempFilePath;
		innerAudioContext.onPlay(() => {
			console.log('开始播放')
		})
		innerAudioContext.onError((res) => {
			console.log(res.errMsg)
			console.log(res.errCode)
		})
	},
	//启动录制
	record() {
		wx.authorize({
			scope: "scope.record",
			success: function() {
				const options = {
					duration: 600000,
					sampleRate: 44100,
					numberOfChannels: 1,
					encodeBitRate: 192000,
					format: 'mp3',
					frameSize: 50
				}
				recorderManager.start(options)
				recorderManager.onStart(() => {
					console.log('recorder start')
				})
				recorderManager.onError((res) => {
					console.log(res);
				})
			}
		})
	},
})

猜你喜欢

转载自blog.csdn.net/oyy_1126/article/details/103182645