我正在开发一个 C# 应用程序,我需要从给定的 URL 获取视频文件的持续时间。视频文件在线托管,我需要以编程方式获取它们的持续时间。
我在网上搜索过,但没有找到在 C# 中执行此操作的明确解决方案。我发现的大多数示例都涉及使用第三方库。有人可以指导我如何在没有任何库的情况下实现这一目标吗?
这是我迄今为止尝试过的: 媒体信息库: FFMpeg: Http客户端:
代码片段:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string videoUrl = "https://example.com/video.mp4";
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(videoUrl);
if (response.IsSuccessStatusCode)
{
byte[] videoData = await response.Content.ReadAsByteArrayAsync();
}
}
}
}
我建议您通过两种方法从 URL 获取视频文件的视频时长。
使用C#(需要包含shell对象dll)
[STAThread] // Add STAThread attribute here
public static string GetVideoDuration(string filepath)
{
string formatedduration = "";
// Create Shell32 Shell object
Shell shell = new ShellClass();
// Get the folder that contains the video file
Folder folder = shell.NameSpace(System.IO.Path.GetDirectoryName(filepath));
// Get the video file
FolderItem folderItem = folder.ParseName(System.IO.Path.GetFileName(filepath));
// Get the duration property
string duration = folder.GetDetailsOf(folderItem, 27); // 27 is the index of the "Duration" property
formatedduration = GetTimeFormat(duration);
return formatedduration;
}
private static string GetTimeFormat(string timeformat)
{
// Split the time format string into hours, minutes, and seconds
string[] parts = timeformat.Split(':');
// Parse hours, minutes, and seconds
int hours = int.Parse(parts[0]);
int minutes = int.Parse(parts[1]);
int seconds = int.Parse(parts[2]);
// Construct TimeSpan object
TimeSpan timeSpan = new TimeSpan(hours, minutes, seconds);
string formattedTime = "";
if (timeSpan.Hours != 0)
{
formattedTime += $"{hours}hr{(hours != 1 ? "s" : "")} ";
}
if (timeSpan.Minutes != 0)
{
formattedTime += $"{minutes}min";
}
if (timeSpan.Seconds != 0)
{
formattedTime += $"{seconds}sec";
}
return formattedTime;
}
使用Javascript
<video id="videoId" width="1920" height="1080" controls>
<source src="yourVideoURL.mp4" type="video/mp4">
</video>
<script>
let videoTag = document.getElementById("videoId");
alert(vidTag.duration);
</script>