Search code examples
c#libvlc

How can I use libvlc in c# to tell the duration of an audio file without playing it?


I'm using libvlc in a .netcore project to simply play .ogg and .wav files like this:

using Vlc.DotNet.Core;
...

namespace Test
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            string vlcPath;

            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\VideoLAN\VLC"))
              vlcPath = key.GetValue("InstallDir").ToString();

            vlcPlayer = new VlcMediaPlayer(new DirectoryInfo(vlcPath));
            vlcPlayer.Play(songFilename);
            ...

I would think doing something like vlcPlayer.SetMedia(songFilename) before using the .Play() method, would set the vlcPlayer object members with info relevant to the clip, but it doesn't. Is there an uncomplicated way to get duration using this library?


Solution

  • First, I needed to use the .Parse() method after setting the player's media item like this:

    FileInfo info = new FileInfo(songFilename);
    vlcPlayer.SetMedia(info);
    vlcPlayer.Parse();
    

    But, it appears there is a bug in the latest Vlc.DotNet.Core (v3.1.0), such that the .Parse () method does not work as it should. For one, there is no class member to find out the state of the parsing operation, and it never seems to complete if I take a look at the Duration property, which never changes from -1.

    Instead, I found LibVLCSharp that works great. Here's the code that worked for me that allowed me to work with the media item outside of a player object altogether:

    var media = new Media(libvlc, new Uri(songFilename));
    media.Parse();
    while (media.ParsedStatus != MediaParsedStatus.Done) Thread.Sleep(10);
    

    Afterwards, media.Duration is correct.