问题描述
下载视频和音频后,我使用 react-native-ffmpeg 来获取最终的视频文件。有用。当我得到最终的视频文件时,我想删除 1.mp4 和 2.mp4。问题是 await getFinalVideo(path,path1,path2,titleVideo) 之后的代码没有运行。 1.mp4 和 2.mp4 仍然存在于文件系统中。如何解决?我的错在哪里?
import React from "react";
import { PermissionsAndroid } from "react-native";
import RNFS from "react-native-fs";
import { LogLevel,RNFFmpeg } from "react-native-ffmpeg";
// url1 video,url2 audio
export const fetchDashFile = async (url1,url2,title) => {
let options1 = {
method: "GET",headers: {},};
let options2 = {
method: "GET",};
let path = RNFS.DownloadDirectoryPath + "/";
let path1 = path + "1" + ".mp4";
let path2 = path + "2" + ".mp4";
const beginVideo = (res) => {
console.log("start download video file");
};
const beginAudio = (res) => {
console.log("start download audio file");
};
const progressVideo = (res) => {
let percentage = ((100 * res.bytesWritten) / res.contentLength) | 0;
console.log(percentage);
};
const progressAudio = (res) => {};
let DownloadFileOptions1 = {
fromUrl: url1,toFile: path1,headers: options1.headers,background: true,connectionTimeout: 50,progressInterval: 1,progressDivider: 10,begin: beginVideo,progress: progressVideo,};
let DownloadFileOptions2 = {
fromUrl: url2,toFile: path2,headers: options2.headers,begin: beginAudio,progress: progressAudio,};
try {
await Promise.all([
RNFS.downloadFile(DownloadFileOptions1).promise,RNFS.downloadFile(DownloadFileOptions2).promise,]);
let titleVideo = Date.Now().toString();
await getFinalVideo(path,titleVideo);
if (RNFS.exists(path1)) {
console.log("delete 1");
await RNFS.unlink(path1);
}
if (RNFS.exists(path2)) {
console.log("delete 2");
await RNFS.unlink(path2);
}
} catch (e) {
alert("error,please try again");
}
};
function getFinalVideo(path,name) {
let command =
"-i " + path1 + " -i " + path2 + " -c copy " + path + name + ".mp4";
return new Promise((resovle,reject) => {
RNFFmpeg.executeAsync(command,(completedExecution) => {
if (completedExecution.returnCode === 0) {
console.log("FFmpeg process completed successfully");
} else {
console.log(
`FFmpeg process Failed with rc=${completedExecution.returnCode}.`
);
}
})
.then((executionId) => {
console.log(executionId);
Promise.resolve("success");
})
.catch((e) => {
console.log("wrong happened when doing ffmpeg" + e);
Promise.reject(e);
});
});
}
解决方法
我太笨了。在删除文件之前,需要等待 ffmpeg 工作完成!我对 Promise 有一些误解。所以这是正确的代码。
...
let titleVideo = Date.now().toString()
await getFinalVideo(path,path1,path2,titleVideo)
...
async function getFinalVideo(path,name) {
let command = '-i ' + path1 + ' -i ' + path2 + ' -c copy ' + path + name + '.mp4'
await RNFFmpeg.executeAsync(command,completedExecution => {
if (completedExecution.returnCode === 0) {
console.log("FFmpeg process completed successfully");
} else {
console.log(`FFmpeg process failed with rc=${completedExecution.returnCode}.`)
}
})
.then(executionId => {
console.log(executionId)
// RNFFmpeg.cancelExecution(executionId)
})
.catch(e => {
console.log('wrong happened when doing ffmpeg' + e)
})