<template>
    <view>
		<view class="VoiceModel" v-show="VoiceModel">
			<view class="container" @touchstart="startRecord" @touchend="endRecord">
				<text class="zhcx-iconfont zhcx-icon-yuyin"></text>
				<view class="status">{{status}}</view>
			</view>
		</view>
    </view>
</template>

<script>
	import {notEmpty} from '@/libs';
	import config from '@/config';
	const speechConfig=config.baidu.speech;
	const speechAppId=speechConfig.appId;
	const speechApiKey=speechConfig.apiKey;
	const speechSecretKey=speechConfig.secretKey;
	
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();	
	innerAudioContext.autoplay = true;

	export default {
		name:'speech-baidu',
		data() {
			return {
				text: 'uni-app',
				voicePath: '',
				fileSize:0,
				word:"",
				VoiceModel:false,
				status:"长按开始录音"
			}
		},
		created() {
			this.$nextTick(()=>{
				recorderManager.onStop(res=>{
					console.log('recorder stop' + JSON.stringify(res));
					uni.showToast({
						title:"录音结束！"
					})
					this.status="录音结束";
					this.voicePath = res.tempFilePath;
					this.fileSize=res.fileSize;
					this.startYuyin();
				});				
			})
		},
		methods: {
			startRecordHanlle(){
				this.VoiceModel=true;
			},
			startRecord() {
				this.status="开始录音";
				recorderManager.start();
				setTimeout(()=>{
					this.endRecord()
				},60000)
			},
			endRecord() {
				console.log('录音结束')
				// #ifdef H5
				
					return;
				// #endif
				this.status="录音结束";
				recorderManager.stop();
				setTimeout(()=>{
					this.VoiceModel=false;
				},600)
			},
			playVoice() {
				console.log('播放录音');
				if (this.voicePath) {
					innerAudioContext.src = this.voicePath;
					innerAudioContext.play();
				}
			},
			async startYuyin() {
				console.log('识别中……')
				uni.showLoading({
					title: '识别中……'
				});
				let adioFileData=await this.Audio2dataURL(this.voicePath);
				let {access_token}=await this.getToken();
				let result=await this.ConversionWords({
					format: 'm4a', //语音文件的格式，pcm/wav/amr/m4a。不区分大小写。推荐pcm文件
					rate: 16000, //	采样率，16000，固定值 此处文档参数16000，达不到这种高保真音频，故 使用8000
					// dev_pid: 1537,//普通话
					channel: 1, //声道数，仅支持单声道，请填写固定值 1
					cuid: 'zhcxcuid', //用户唯一标识，用来区分用户，计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码，长度为60字符以内。
					token:access_token,
					speech:adioFileData, //本地语音文件的的二进制语音数据 ，需要进行base64 编码。与len参数连一起使用。
					len: this.fileSize //本地语音文件的的字节数，单位字节 init
				})
				
				if(result.statusCode===200){
					let word=result.data.result[0];
					if(notEmpty(word)){
						this.$emit('success',result)
					}else{
						uni.showToast({
							icon:"none",
							title:"未识别到文字！"
						})	
						this.status="未识别到文字";
					}
				}else{
					uni.showToast({
						icon:"none",
						title:"语音识别失败"
					})
					this.status="语音识别失败";
				}
			},
			getToken(){
				return new Promise((resolve,reject)=>{
					//获取token
					uni.request({
						url: 'https://openapi.baidu.com/oauth/2.0/token', //仅为示例，并非真实接口地址。
						data: {
							grant_type: 'client_credentials',
							client_id: speechApiKey,
							client_secret:speechSecretKey,
						},
						header: {
							'content-type': 'application/json;charset=utf-8' //自定义请求头信息
						},
						success: (res) => {
							resolve(res.data)
						},
						fail(err) {
							uni.showToast({
								icon:"none",
								title:"语音识别失败"
							})
							this.status="语音识别失败";
							uni.hideLoading();						
							reject(err)
						}
					});				
				})
			},
			ConversionWords(postData) {
				//调用语音识别接口
				return new Promise((resolve,reject)=>{
					uni.request({
						url: 'https://vop.baidu.com/server_api', //仅为示例，并非真实接口地址。
						data: postData,
						header: {
							"Content-Type":"application/json" //自定义请求头信息
						},
						method: 'POST',
						success: (res) => {
							resolve(res)
						},
						fail(err) {
							uni.showToast({
								icon:"none",
								title:"语音识别失败"
							})	
							this.status="语音识别失败";					
							reject(err)
						},
						complete() {
							uni.hideLoading();
						}
					})				
				})
			},
			Audio2dataURL(path) {
				return new Promise((resolve,reject)=>{
					const FMS = uni.getFileSystemManager();
					FMS.readFile({
					  filePath:this.voicePath,
					  encoding: 'base64',
					  success(response) {
						resolve(response.data)
					  },
					  fail(err){
						uni.showToast({
							icon:"none",
							title:"语音识别失败"
						})
						this.status="语音识别失败";					  
						uni.hideLoading();
						reject(err)
					  }
					})	
					// plus.io.resolveLocalFileSystemURL(path, function(entry) {
					// 	entry.file(function(file) {
					// 		var reader = new plus.io.FileReader();
					// 		_this.adioSize = file.size;
					// 		reader.onloadend = function(e) {
					// 			console.log(e.target.result);
					// 			console.log(e.target.result.split(",")[1]);
					// 			resolve({
					// 				voice:e.target.result.split(",")[1]
					// 			})
					// 		};
					// 		reader.readAsDataURL(file);
					// 	}, function(e) {
					// 		reject(e.message)
					// 		console.log("读写出现异常: " + e.message);
					// 	})
					// })					
				})

			}
		}
	}
</script>

<style lang="scss" scoped>
	.word-cont{
		height: 200upx;
		overflow-y: auto;
		border-bottom:1px solid #ccc;
	}
	.startRecordHanlle{
		width:280upx;
		margin: 100upx auto;
		background-color: #0081ff;
		color: #fff;
		.zhcx-icon-yuyin{
			font-size: 46upx;
			padding-right: 10upx;
		}
	}
	.VoiceModel{
		width: 100%;
		height: 100%;
		position: fixed;
		left: 0;
		top: 0;
		background-color: rgba(0,0,0,0.6);
		z-index: 999;
		.container{
			width: 240upx;
			height: 320upx;
			border-radius: 10upx;
			background-color:#fff;
			box-shadow:0 0 2upx rgba(0,0,0,0.6);
			position: fixed;
			left: 50%;
			top:280upx;
			transform: translateX(-50%);
			z-index: 999;
			text-align: center;
			display: flex;
			justify-content: space-between;
			align-items: center;
			flex-direction: column;
			.zhcx-icon-yuyin{
				color: #17b18f;
				font-size: 200upx;
			}
			.status{
				color:#17b18f;
				padding-bottom: 10upx;
			}
		}
	}
</style>
