无法访问该文件,因为它正被另一个使用 ffmpeg 的进程使用

Cannot access the file because it is being used by another process using ffmpeg

我遇到错误:

Cannot access the file because it is being used by another process

我有一个 C# 桌面应用程序。

我正在使用进程 class 通过 FFMPEG 将图像转换为视频文件。

这是我的代码:

using (Process serverBuild = new Process())
{
    serverBuild.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
    string args = " -f image2  -i " + {path} + "\img%05d.jpg -s 352x288  -filter:v \"setpts=5.0*PTS\" -y " + {path}\File.mp4;

    serverBuild.StartInfo.Arguments = args;
    serverBuild.StartInfo.FileName = "ffmpeg.exe";
    serverBuild.StartInfo.UseShellExecute = false;
    serverBuild.StartInfo.RedirectStandardOutput = true;
    serverBuild.StartInfo.RedirectStandardError = true;
    serverBuild.StartInfo.CreateNoWindow = true;
    serverBuild.Start();
    //  string output = serverBuild.StandardOutput.ReadToEnd();
    //Log.Instance.Debug(serverBuild.StandardError.ReadToEnd());
    serverBuild.WaitForExit();
    serverBuild.Close();

}

 Directory.Delete(ExportRoute + FFMPEGPacket.LicenseKey + "\" + FFMPEGPacket.Guid, true);

//which raise the error..

图片都被删除了,但File.Mp4没有,这就是错误。报错说新建的MP4文件不能删除

注意 这是说明错误的部分代码

试试看:

File.WriteAllBytes(path, new byte[0]);
File.Delete(path);

FFMPEG 关闭后可能仍在渲染从图像创建的视频,因此如果放置 Threading.Thead.Sleep(5000) 5 秒可能是值得的;删除前。

您可以尝试使用以下代码创建文件(对我有用):

        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = exe_path;
        // replace your arguments here
        psi.Arguments = string.Format(@" arguments ") 

        psi.CreateNoWindow = true;
        psi.ErrorDialog = true;
        psi.UseShellExecute = false;
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardInput = false;
        psi.RedirectStandardError = true;
        Process exeProcess = Process.Start(psi);
        exeProcess.PriorityClass = ProcessPriorityClass.High;
        string outString = string.Empty;
        exeProcess.OutputDataReceived += (s, e) =>
        {
            outString += e.Data;
        };
        exeProcess.BeginOutputReadLine();
        string errString = exeProcess.StandardError.ReadToEnd();
        Trace.WriteLine(outString);
        Trace.TraceError(errString);
        exeProcess.WaitForExit();
        exeProcess.Close();
        exeProcess.Dispose();