Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

.NET6同时调用多个FFmpeg命令拉取视频流

  1. User

    .NET6同时调用多个FFmpeg命令拉取视频流

  2. Assistant

    如果您想使用.NET 6同时调用多个FFmpeg命令拉取视频流,则可以使用.NET的System.Diagnostics.Process类和System.Threading.Tasks.Task类。

    以下是一个示例代码,它可以同时调用3个FFmpeg命令拉取3个不同的视频流:

    using System;
    using System.Diagnostics;
    using System.Threading.Tasks;
     
    namespace MultiFFmpegDemo
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var stream1 = "rtsp://url1";
                var stream2 = "rtsp://url2";
                var stream3 = "rtsp://url3";
     
                // create tasks for ffmpeg commands
                var task1 = Task.Run(() => StartFFmpegProcess(stream1, "output1.mp4"));
                var task2 = Task.Run(() => StartFFmpegProcess(stream2, "output2.mp4"));
                var task3 = Task.Run(() => StartFFmpegProcess(stream3, "output3.mp4"));
     
                // wait for all tasks to finish
                await Task.WhenAll(task1, task2, task3);
     
                Console.WriteLine("All FFmpeg commands finished.");
            }
     
            static void StartFFmpegProcess(string inputUrl, string outputFile)
            {
                // set up the process start info
                var processStartInfo = new ProcessStartInfo("ffmpeg.exe")
                {
                    Arguments = $"-i {inputUrl} -codec copy -f mp4 {outputFile}",
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                };
     
                // start the process and read output/error streams
                using var process = Process.Start(processStartInfo);
                process.OutputDataReceived += (_, e) => Console.WriteLine($"FFmpeg output: {e.Data}");
                process.ErrorDataReceived += (_, e) => Console.WriteLine($"FFmpeg error: {e.Data}");
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
     
                // wait for the process to finish
                process.WaitForExit();
            }
        }
    }
    

    在此示例中,我们使用StartFFmpegProcess方法来启动ffmpeg进程并运行输入的ffmpeg命令。我们使用Task.Run方法将此方法包装在一个Task对象中,并将其传递给Task.WhenAll方法,以便同时启动多个ffmpeg进程。最后,我们使用await关键字等待所有的任务完成。

    请注意,您需要将示例中的输入和输出URL(stream1,output1.mp4等)替换为您自己的URL和输出文件名。此外,您还需要将ffmpeg.exe的路径设置为环境变量或相应位置的路径。