C# 获取本地mp4文件的视频总时长秒数
时间: 2023-10-08 07:08:39 浏览: 110
你可以通过使用Windows Media Format SDK来获取本地mp4文件的视频总时长秒数。以下是一个C#代码示例:
```csharp
using WMPLib;
public static double GetVideoLength(string filePath)
{
WindowsMediaPlayer wmp = new WindowsMediaPlayer();
IWMPMedia media = wmp.newMedia(filePath);
return media.duration;
}
```
这个脚本将返回指定路径的MP4文件的长度,单位为秒。你可以将视频路径设置为“filePath”变量的值。请注意,这个方法需要Windows Media Player安装在你的计算机上。
相关问题
C# 不额外安装,获取本地mp4文件的视频总时长秒数
你也可以使用FFmpeg库来获取本地mp4文件的视频总时长秒数,而不需要额外安装任何软件。以下是一个C#代码示例:
```csharp
using System.Diagnostics;
public static double GetVideoLength(string filePath)
{
double length = 0;
Process process = new Process();
process.StartInfo.FileName = "ffmpeg";
process.StartInfo.Arguments = "-i " + filePath + " -v quiet -print_format json -show_format";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
string[] lines = output.Split('\n');
foreach (string line in lines)
{
if (line.Contains("duration"))
{
double.TryParse(line.Substring(line.IndexOf("duration") + 10), out length);
break;
}
}
return length;
}
```
这个脚本将返回指定路径的MP4文件的长度,单位为秒。你可以将视频路径设置为“filePath”变量的值。请注意,这个方法需要在你的计算机上安装FFmpeg库。
C# 不额外安装库,获取本地mp4文件的视频总时长秒数
你可以使用 System.Windows.Forms.MediaPlayer 类来获取本地 mp4 文件的视频总时长秒数。以下是一个示例代码块:
```csharp
using System.Windows.Forms;
namespace VideoPlayer
{
class Program
{
static void Main(string[] args)
{
// 创建一个新的 MediaPlayer 实例
var player = new MediaPlayer();
// 打开本地 mp4 文件
player.Open(new Uri("your_mp4_file_path"));
// 等待视频加载完成
while (player.NaturalDuration.TimeSpan.TotalSeconds == 0)
{
continue;
}
// 获取视频总时长秒数
double totalSeconds = player.NaturalDuration.TimeSpan.TotalSeconds;
// 关闭 MediaPlayer 实例
player.Close();
}
}
}
```
在上面的示例代码中,我们首先创建了一个新的 MediaPlayer 实例,并使用 Open 方法打开本地 mp4 文件。然后,我们使用一个 while 循环等待视频加载完成(因为需要加载视频才能获取视频的总时长)。在加载完成后,我们使用 NaturalDuration 属性获取视频的总时长,并将其转换为秒数。最后,我们使用 Close 方法关闭 MediaPlayer 实例。