CSharp下载ffpmeg

ffmpeg csharp 文章 2024-01-16 21:29 196 0 全屏看文

AI助手支持GPT4.0

先定义这个方法:

private async Task CheckFfmpegAsync()
{
    string ffmpegPath = Path.Combine(_workingDirectory, "ffmpeg");
    if (!Directory.Exists(ffmpegPath))
    {
        Directory.CreateDirectory(ffmpegPath);
    }
    FFmpeg.SetExecutablesPath(ffmpegPath);
    _logger.Information("Checking FFmpeg...");
    if (Directory.GetFiles(ffmpegPath).Length == 0)
    {
        _logger.Information("FFmpeg not found - downloading...");
        
        await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official, FFmpeg.ExecutablesPath, new FFMpegDownloadingProgress(Log.Logger));
        _logger.Information("FFmpeg downloaded");
        if (Environment.OSVersion.Platform == PlatformID.Unix)
        {
            Exec("chmod +x " + Path.Combine(ffmpegPath, "ffmpeg"));
            Exec("chmod +x " + Path.Combine(ffmpegPath, "ffprobe"));
        }
    }
}

image.png

然后在代码里使用

private async Task CheckFfmpegAsync()
{
    string ffmpegPath = Path.Combine(_workingDirectory, "ffmpeg");
    if (!Directory.Exists(ffmpegPath))
    {
        Directory.CreateDirectory(ffmpegPath);
    }
    FFmpeg.SetExecutablesPath(ffmpegPath);
    _logger.Information("Checking FFmpeg...");
    if (Directory.GetFiles(ffmpegPath).Length == 0)
    {
        _logger.Information("FFmpeg not found - downloading...");
        
        await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official, FFmpeg.ExecutablesPath, new FFMpegDownloadingProgress(Log.Logger));
        _logger.Information("FFmpeg downloaded");
        if (Environment.OSVersion.Platform == PlatformID.Unix)
        {
            Exec("chmod +x " + Path.Combine(ffmpegPath, "ffmpeg"));
            Exec("chmod +x " + Path.Combine(ffmpegPath, "ffprobe"));
        }
    }
}


这样的话就会判断有没有下载ffmpeg没有就会下载:

image.png

然后就可以使用CMD执行了。

private void Exec(string cmd)
{
    var escapedArgs = cmd.Replace("\"", "\\\"");

    using var process = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true,
            WindowStyle = ProcessWindowStyle.Hidden,
            FileName = "/bin/bash",
            Arguments = $"-c \"{escapedArgs}\""
        }
    };

    try
    {
        process.Start();
        process.WaitForExit();
    }
    catch (Exception ex)
    {
        _logger.Error(ex, "Error occurred while executing command: {cmd}", cmd);
    }
}

指定代码:

await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official, FFmpeg.ExecutablesPath, new FFMpegDownloadingProgress(Log.Logger));
_logger.Information("FFmpeg downloaded");
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
    Exec("chmod +x " + Path.Combine(ffmpegPath, "ffmpeg"));
    Exec("chmod +x " + Path.Combine(ffmpegPath, "ffprobe"));
}


-EOF-

AI助手支持GPT4.0


您还可能感兴趣的文章