<template>
  <div class="ffmpeg">
		<input type="file" @change="onFileChange" accept="video/mp4" />
		<button @click="extractAudio()" :disabled="!videoFile">提取音频</button>
		<audio v-if="audioUrl" :src="audioUrl" controls></audio>
	</div>
</template>

<script>
import FFmpeg from "@ffmpeg/ffmpeg";
const { createFFmpeg, fetchFile } = FFmpeg;

const ffmpeg = createFFmpeg({
	corePath: './static/ffmpeg/ffmpeg-core.js',
	log: true,
});

export default {
	data() {
		return {
			videoFile: null,
			audioUrl: null
		};
	},
	methods: {
		async onFileChange(event){
			this.videoFile = event.target.files[0];
		},
		async extractAudio(file) {//提取音频
			return new Promise(async(resolve) => {
				try {
					file = file || this.videoFile;
					if (!file){
						window.parent.postMessage({code:1,msg:'请选择视频文件'},'*');
						resolve({code:1,msg:'请选择视频文件'});
						return;
					};

					// 加载FFmpeg
					if (!ffmpeg.isLoaded()) {
						await ffmpeg.load();
					}

					// 将视频文件加载到FFmpeg
					ffmpeg.FS("writeFile", "input.mp4", await fetchFile(file));

					// 提取音频
					await ffmpeg.run(
						"-i",
							"input.mp4",
							"-q:a",
							"0",
							"-map",
							"a",
							"output.mp3"
					);

					// 从FFmpeg文件系统中读取音频文件
					const data = ffmpeg.FS("readFile", "output.mp3");

					// 创建音频URL
					let audioBlob = new Blob([data.buffer], { type: "audio/mp3" });
					audioBlob.name = "output.mp3"
					if(this.videoFile){
						this.audioUrl = URL.createObjectURL(audioBlob);
					}
					let resultFile = new File([audioBlob], "output.mp3", { type: "audio/mp3" });
					window.parent.postMessage({code:0,msg:'提取音频成功',file:resultFile},'*');
					resolve({file:audioBlob});
				} catch (error) {
					console.log(error);
					window.parent.postMessage({code:1,msg:'提取音频失败',error:error},'*');
					resolve({code:1,msg:'提取音频失败',error:error});
				}
			})
		},
	},
	mounted(){
		window.addEventListener('message',(e)=>{
			let _data = e.data;
			if(_data.type === 'extractAudio'){
				this.extractAudio(_data.file);
			}
		})
	}
};
</script>

<style scoped>
.ffmpeg {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
}
</style>
