<template>
	<view class="demo_index_page">
		<view class="page_content">
			<view class="margin-lr-30">
				<button @tap="startRecord" class="jc-avatar-200 bg-main text-center text-32 text-ff"
					style="line-height: 200rpx;" v-if="!isRecording">开始录音</button>
				<button @tap="endRecord" class="jc-avatar-200 bg-auxiliary text-center text-32 text-ff"
					style="line-height: 200rpx;" v-if="isRecording">停止录音</button>
				<button @tap="playVoice"
					class="margin-top-30 line-height-90 radius-10 bg-auxiliary text-28 text-ff">播放录音</button>
			</view>
		</view>
	</view>
</template>

<script>
	import record from "@/components/hzjc/utils/functions/record.js"
	const recorderManager = uni.getRecorderManager()
	const innerAudioContext = uni.createInnerAudioContext()

	innerAudioContext.autoplay = true
	export default {
		data() {
			return {
				isRecording: false, //录音状态 false--没有录音 true--录音中
				voicePath: '' //录音文件的临时路径
			}
		},

		onReady() {
			//监听录音停止事件，会回调文件地址
			recorderManager.onStop((res) => {
				console.log('--onStop--')
				console.log(JSON.stringify(res))
				this.isRecording = false //设置录音状态为没有录音
				this.voicePath = res.tempFilePath //获取录音文件的临时路径

				// 上传录音文件到OSS
				record.uploadRecordFile(res.tempFilePath).then(res => {
					console.log(res)
					let path = res[0]
					// 录音文件
					this.voiceUrl = path
				})
			})

			//监听录音错误事件, 会回调错误信息
			recorderManager.onError((res) => {
				console.log('--onError--')
				console.log('recorder error' + JSON.stringify(res))
			})
		},

		methods: {
			/**
			 * 开始录音
			 * 2022-05-06
			 */
			startRecord() {
				console.log(1)
				// 判断授权
				record.isAuth().then(res => {
					// 没有授权，调用录音接口弹出授权，并立即停止录音
					if (!res) {
						return false
					} else {
						console.log(2)
						this.isRecording = true
						record.record().then(res => {
							console.log(3)

						})
					}
				})
			},

			/**
			 * 停止录音
			 * 2022-05-06
			 */
			endRecord() {
				// 停止录音
				record.stopRecord(0)
			},

			/**
			 * 播放录音
			 * 2022-05-06
			 */
			playVoice() {
				console.log('播放录音')

				if (this.voicePath) {
					innerAudioContext.src = this.voicePath
					innerAudioContext.play()
				}
			}
		}
	}
</script>

<style scoped>
</style>
