C# get video duration

Here is the HTML content for your query “c# get video duration”:

“`html

Getting Video Duration in C#

To get the duration of a video in C#, you can use the MediaElement class from Windows Presentation Foundation (WPF). Here’s an example:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace VideoDurationExample
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            
            // Set the source of the MediaElement to your video path
            mediaElement.Source = new Uri("path_to_your_video.mp4");
            mediaElement.MediaOpened += MediaElement_MediaOpened;
        }
        
        private void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            // Get the duration of the video in TimeSpan format
            TimeSpan duration = mediaElement.NaturalDuration.TimeSpan;
            
            // Display the duration in a label or any other control
            durationLabel.Content = "Duration: " + duration.ToString(@"hh\:mm\:ss");
        }
    }
}
    

In the above example, we have created a WPF window with a MediaElement and a label control. We set the source of the MediaElement to the path of the video file. When the media is opened, the MediaElement_MediaOpened event handler is triggered, and we can access the duration of the video using the NaturalDuration property of the MediaElement.

The duration is returned in a TimeSpan format, which represents a length of time. We can then display this duration in a label or any other control on the UI.

Note: To use the MediaElement class, you need to add a reference to the PresentationCore and PresentationFramework assemblies in your project.

“`

In the above HTML content, I have provided a detailed explanation of how to get the duration of a video in C#. I have also included an example code snippet that demonstrates the usage of the `MediaElement` class from Windows Presentation Foundation (WPF). The code sets the source of `MediaElement` to your video file and retrieves the duration using the `NaturalDuration` property. Finally, it displays the duration in a label control.

Read more interesting post

Leave a comment