代码之家  ›  专栏  ›  技术社区  ›  Optidev

如何在asp.net C#中获取视频文件的视频持续时间?

  •  2
  • Optidev  · 技术社区  · 1 年前

    我有一个应用程序,我们正在上传视频并使用它在社交媒体上发布。我们可以上传视频并播放,但需要存储文件大小和视频持续时间等元信息。我们可以很容易地计算文件大小,但无法获得持续时间。我们尝试了一种使用javascript的方法,但它并不那么可靠。有人能建议一种在不使用外部第三方库的情况下获取视频时长的方法吗?

    我们尝试的是创建html视频标签,并在标签渲染后获得持续时间。但它的作用并不一致。

    1 回复  |  直到 1 年前
        1
  •  3
  •   Optidev    1 年前

    我们可以使用Microsoft shell对象dll来实现这一点。将shell32引用添加到引用中的项目,然后参考下面的代码。

        [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;
        }
    

    调用上述方法,如下所示:

     //Create thread for shellobject 
      Thread thread = new Thread(() => { VideoDuration = GetVideoDuration(Server.MapPath(fileURL)); });
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start();
      thread.Join();
      thread.Abort();