一、安装方法
1.1 使用yarn进行安装
yarn add @ffmpeg/ffmpeg @ffmpeg/core
1.2 安装版本
注意安装版本需在0.12.0以上版本才可以使用下面代码(目前更新到0.12.10),之前的版本代码使用方法有所不同(0.12.10之后的版本也可能会有变动)
二、代码
1.1 引用和声明
import { FFmpeg } from "@ffmpeg/ffmpeg";const ffmpeg = new FFmpeg();
1.2 加载
if (!isLoadFfmpegCore) {messageText.value = "加载ffmpeg-core.js";await ffmpeg.load({coreURL: "/static/esm/ffmpeg-core.js", });isLoadFfmpegCore = true;}
1.3 对url格式的网络视频转码
const changeFormat = async (url) => {const response = await fetch(url);const blob = await response.blob();const name = "1.mp4";if (!isLoadFfmpegCore) {messageText.value = "加载ffmpeg-core.js";await ffmpeg.load({coreURL: "/static/esm/ffmpeg-core.js",});isLoadFfmpegCore = true;}await ffmpeg.writeFile(name, new Uint8Array(await readFromBlobOrFile(blob)));await ffmpeg.exec(["-i", name, `${111}.mp4`]);isTranscoding = false;const data = await ffmpeg.readFile(`${111}.mp4`);videoSrc.value = URL.createObjectURL(new Blob([data.buffer], { type: "video/mp4" }));
};
const readFromBlobOrFile = (blob) =>new Promise((resolve, reject) => {const fileReader = new FileReader();fileReader.onload = () => {resolve(fileReader.result);};fileReader.onerror = ({target: {error: { code },},}) => {reject(Error(`File could not be read! Code=${code}`));};fileReader.readAsArrayBuffer(blob);});
1.4 对本地文件视频转码
其他代码与网络视频类似,这里贴出读取文件代码
const fetchFile = async (_data) => {let data = _data;if (typeof _data === "undefined") {return new Uint8Array();}if (typeof _data === "string") {/* From base64 format */if (/data:_data\/([a-zA-Z]*);base64,([^"]*)/.test(_data)) {data = atob(_data.split(",")[1]).split("").map((c) => c.charCodeAt(0));/* From remote server/URL */} else {const res = await fetch(new URL(_data, import.meta.url).href);data = await res.arrayBuffer();}/* From Blob or File */} else if (_data instanceof File || _data instanceof Blob) {data = await readFromBlobOrFile(_data);}return new Uint8Array(data);
};