What's the best way to get video metadata from a video file in ASP.Net MVC using C#?

后端 未结 4 1458
囚心锁ツ
囚心锁ツ 2020-12-05 05:36

I\'ve been searching on Google and StackOverflow for a good couple of hours. There seems to be a lot of similar questions on StackOverflow but they are all about 3-5 years o

4条回答
  •  难免孤独
    2020-12-05 06:19

    I suggest you use ffmpeg with Process.Start, the code looks like follows:

        private string GetVideoDuration(string ffmpegfile, string sourceFile) {
            using (System.Diagnostics.Process ffmpeg = new System.Diagnostics.Process()) {
                String duration;  // soon will hold our video's duration in the form "HH:MM:SS.UU"
                String result;  // temp variable holding a string representation of our video's duration
                StreamReader errorreader;  // StringWriter to hold output from ffmpeg
    
                // we want to execute the process without opening a shell
                ffmpeg.StartInfo.UseShellExecute = false;
                //ffmpeg.StartInfo.ErrorDialog = false;
                ffmpeg.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                // redirect StandardError so we can parse it
                // for some reason the output comes through over StandardError
                ffmpeg.StartInfo.RedirectStandardError = true;
    
                // set the file name of our process, including the full path
                // (as well as quotes, as if you were calling it from the command-line)
                ffmpeg.StartInfo.FileName = ffmpegfile;
    
                // set the command-line arguments of our process, including full paths of any files
                // (as well as quotes, as if you were passing these arguments on the command-line)
                ffmpeg.StartInfo.Arguments = "-i " + sourceFile;
    
                // start the process
                ffmpeg.Start();
    
                // now that the process is started, we can redirect output to the StreamReader we defined
                errorreader = ffmpeg.StandardError;
    
                // wait until ffmpeg comes back
                ffmpeg.WaitForExit();
    
                // read the output from ffmpeg, which for some reason is found in Process.StandardError
                result = errorreader.ReadToEnd();
    
                // a little convoluded, this string manipulation...
                // working from the inside out, it:
                // takes a substring of result, starting from the end of the "Duration: " label contained within,
                // (execute "ffmpeg.exe -i somevideofile" on the command-line to verify for yourself that it is there)
                // and going the full length of the timestamp
    
                duration = result.Substring(result.IndexOf("Duration: ") + ("Duration: ").Length, ("00:00:00").Length);
                return duration;
            }
        }
    

    May it helps.

提交回复
热议问题