使用ffmpeg或ffprobe结合VB.NET获取视频时长
用FFmpeg/FFprobe结合VB.NET获取视频时长入门指南
准备工作
- 下载FFmpeg工具包:获取最新的静态编译包(Windows用户选带"full_build"的版本),解压到本地目录(比如
C:\ffmpeg\bin),解压后会得到ffmpeg.exe和ffprobe.exe两个核心程序。 - 路径配置:可以把FFmpeg的bin目录添加到系统环境变量
PATH,这样代码里不用写全路径;如果不添加,必须在代码里指定ffprobe.exe/ffmpeg.exe的完整路径。
方法一:用FFprobe获取(推荐,更轻量高效)
FFprobe是FFmpeg套件中专门用于探测媒体文件元数据的工具,比FFmpeg更适合获取时长这类信息。
FFprobe命令格式
执行以下命令可直接获取视频时长(单位:秒,可能带小数):
ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "你的视频文件路径"
参数说明:
-v error:仅输出错误信息,屏蔽冗余日志-show_entries format=duration:仅提取媒体格式信息中的时长字段-of default=noprint_wrappers=1:nokey=1:简化输出格式,只返回时长数值,不输出多余包裹文本和字段名
VB.NET代码实现
Imports System.Diagnostics Imports System.Globalization Public Class VideoDurationUtils ' 通过FFprobe获取视频时长 Public Shared Function GetDurationWithFFprobe(videoFilePath As String, ffprobeFullPath As String) As TimeSpan Dim procStartInfo As New ProcessStartInfo With { .FileName = ffprobeFullPath, .Arguments = $"-v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 ""{videoFilePath}""", .RedirectStandardOutput = True, .RedirectStandardError = True, .UseShellExecute = False, .CreateNoWindow = True } Using mediaProc As Process = Process.Start(procStartInfo) mediaProc.WaitForExit() ' 读取命令输出的时长字符串 Dim durationOutput As String = mediaProc.StandardOutput.ReadToEnd().Trim() ' 读取错误信息(用于排查问题) Dim errorMsg As String = mediaProc.StandardError.ReadToEnd().Trim() If Not String.IsNullOrEmpty(errorMsg) Then Throw New Exception($"FFprobe错误:{errorMsg}") End If If Double.TryParse(durationOutput, Double.NumberStyles.Any, CultureInfo.InvariantCulture, Dim totalSeconds As Double) Then Return TimeSpan.FromSeconds(totalSeconds) Else Return TimeSpan.Zero End If End Using End Function ' 调用示例 Public Shared Sub TestGetDuration() Dim targetVideo As String = "D:\Media\demo.mp4" Dim ffprobePath As String = "C:\ffmpeg\bin\ffprobe.exe" ' 已加环境变量可直接写"ffprobe.exe" Try Dim videoDuration As TimeSpan = GetDurationWithFFprobe(targetVideo, ffprobePath) Console.WriteLine($"视频时长:{videoDuration.ToString(@"hh\:mm\:ss\.fff")}") Catch ex As Exception Console.WriteLine($"获取时长失败:{ex.Message}") End Try End Sub End Class
方法二:用FFmpeg获取
如果没有单独调用FFprobe的需求,也可以用FFmpeg命令获取时长,命令格式如下:
ffmpeg -i "你的视频文件路径" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1
VB.NET代码实现和FFprobe版本几乎一致,只需把ffprobeFullPath换成ffmpeg.exe的路径即可。
关键注意事项
- 路径空格处理:视频文件路径或FFmpeg工具路径包含空格时,必须用双引号包裹,否则命令执行会失败。
- 错误处理:务必读取
StandardError输出,当视频文件损坏、路径错误或工具不存在时,这里会返回具体错误信息,方便排查问题。 - 时长格式转换:获取的时长是带小数的秒数,可通过
TimeSpan.FromSeconds()转换为时分秒格式,满足不同展示需求。
内容的提问来源于stack exchange,提问作者Sonero41
相关产品推荐
相关产品推荐

