赞
踩
yarn add @ffmpeg/ffmpeg @ffmpeg/core
注意安装版本需在0.12.0以上版本才可以使用下面代码(目前更新到0.12.10),之前的版本代码使用方法有所不同(0.12.10之后的版本也可能会有变动)
- import { FFmpeg } from "@ffmpeg/ffmpeg";
-
- const ffmpeg = new FFmpeg();
- if (!isLoadFfmpegCore) {
- messageText.value = "加载ffmpeg-core.js";
- await ffmpeg.load({
- coreURL: "/static/esm/ffmpeg-core.js",
- });
- isLoadFfmpegCore = true;
- }
- 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);
- });
其他代码与网络视频类似,这里贴出读取文件代码
- 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);
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。