Search code examples
c#mp3file-properties

How can I get the BPM property of an MP3 file in a Windows Forms App


I am trying to get the BPM property from an MP3 file:

enter image description here

I can see how to do this in a Windows Store App as per this question:

How to read Beats-per-minute tag of mp3 file in windows store apps C#?

but can't see how to use Windows.Storage in a Windows Forms app. (If I understand it correctly it's because Windows.Storage is specific to UWP.)

How can I read this in a Forms app? Happy to use a (hopefully free) library if there is nothing native.


Solution

  • You can use Windows' Scriptable Shell Objects for that. The item object has an ShellFolderItem.ExtendedProperty method

    The property you're after is an official Windows property named System.Music.BeatsPerMinute

    So, here is how you can use it (you don't need to reference anything, thanks to the cool dynamic C# syntax for COM objects):

    static void Main(string[] args)
    {
        string path = @"C:\path\kilroy_was_here.mp3";
    
        // instantiate the Application object
        dynamic shell = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
    
        // get the folder and the child
        var folder = shell.NameSpace(Path.GetDirectoryName(path));
        var item = folder.ParseName(Path.GetFileName(path));
    
        // get the item's property by it's canonical name. doc says it's a string
        string bpm = item.ExtendedProperty("System.Music.BeatsPerMinute");
        Console.WriteLine(bpm);
    }