Search code examples
c#windowsperformanceoptimizationvideo

How to get video file duration from video URL


I am working on a C# application where I need to get the duration of a video file from a given URL. The video files are hosted online, and I need to fetch their durations programmatically.

I’ve searched online but haven’t found a clear solution for doing this in C#. Most of the examples I found deal with using 3rd party libraries. Could someone guide me on how to achieve this without any library?

Here is what I’ve tried so far: MediaInfo Library: FFMpeg: HttpClient:

Code Snippet:

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();
               
           }
       }
   }
}

Solution

  • There are two ways I can suggest you to get the video duration of a video file from URL.

    1. Using C#
    2. Using Javascript (In case of a web application and you want it be generated on the fly)

    Using C# (Need to include shell object dll)

    string VideoDuration = string.Empty;
    
    Thread thread = new Thread(() => { VideoDuration = GetVideoDuration(videoPath.Replace("/", "\\")); });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();
    thread.Abort();
    
    [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;
    }
    

    Using 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>