把 ffmpeg 跑在浏览器里。
https://github.com/ffmpegwasm/ffmpeg.wasm
需要设置请求头:
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Opener-Policy: same-origin
安装
npm install @ffmpeg/ffmpeg @ffmpeg/core
将文件转码为 mp4 播放 (ffmpeg.min.js
在 @ffmpeg/ffmpeg
包中):
<body>
<video id="player" controls></video>
<input type="file" id="uploader">
<script src="ffmpeg.min.js"></script>
<script>
const { createFFmpeg, fetchFile } = FFmpeg;
const ffmpeg = createFFmpeg({ log: true });
const transcode = async ({ target: { files } }) => {
const { name } = files[0];
await ffmpeg.load();
ffmpeg.FS('writeFile', name, await fetchFile(files[0]));
await ffmpeg.run('-i', name, 'output.mp4');
const data = ffmpeg.FS('readFile', 'output.mp4');
const video = document.getElementById('player');
video.src = URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' }));
}
document
.getElementById('uploader').addEventListener('change', transcode);
</script>
</body>