import { nextTick } from "vue";

let audioContext = null;
let code = null; // 身份标识
audioContext = uni.createInnerAudioContext(); // 单例模式[3](@ref)
audioContext.onEnded(() => {
	// 播放结束
	uni.$emit('result-audio-ended', code)
})
audioContext.onPlay(() => {
	// 播放
	uni.$emit('result-audio-play', code);
});
audioContext.onError((err) => {
	// 播放
	uni.$emit('result-audio-ended', code)
	uni.showToast({
		title: '音频播放异常，已重置.'
	})
});

const audioList = {
	right: '/static/mp3/newYingyu/right-tip.mp3',
	wrong: '/static/mp3/newYingyu/error-tip.mp3'
}

export const resultImageList = {
	right: '/static/images/study/cjdc/right-tip-img-gif',
	wrong: '/static/images/study/cjdc/error-tip-img-gif'
}

function createAudioNew() {
	audioContext = uni.createInnerAudioContext(); // 单例模式[3](@ref)
	audioContext.onEnded(() => {
		// 播放结束
		uni.$emit('result-audio-ended', code)
	})
	audioContext.onPlay(() => {
		// 播放
		uni.$emit('result-audio-play', code);
	});
	audioContext.onError((err) => {
		// 播放
		console.log('errr',err)
		uni.$emit('result-audio-ended', code);
		uni.showToast({
			title: '音频播放异常，已重置.'
		})
	});
}



export class resultAudioPlayer {
	// 播放音频
	play(codeT, code1) {
		code = {
			code1,
			codeT
		};
		if (audioContext.src === audioList[codeT] && !audioContext.paused) return;
		audioContext.stop();
		audioContext.destroy();
		audioContext = null;
		
		nextTick(() => {
			createAudioNew();
			audioContext.src = audioList[codeT];
			audioContext.play();
		})
	
	}

	// 暂停播放
	pause() {
		audioContext?.pause();
	}

	// 停止播放（释放资源）
	stop() {
		audioContext?.stop();
		audioContext = null;
	}

}