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

蹲街弑〆低调 提交于 2019-12-22 04:26:27

问题


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

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.


回答1:


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



回答2:


There is a version TagLib that was ported to a portable class library (PCL) version that can be referenced by a Windows Forms and used to extract that information.

I referenced the PCL version TagLib#.Portable which is available via Nuget at TagLib.Portable

From there is was a simple matter of opening the file and reading the desired information.

class Example {

    public void GetFile(string path) {
        var fileInfo = new FileInfo(path);
        Stream stream = fileInfo.Open(FileMode.Open);
        var abstraction = new TagLib.StreamFileAbstraction(fileInfo.Name, stream, stream);
        var file = TagLib.File.Create(abstraction);//used to extrack track metadata

        var tag = file.Tag;

        var beatsPerMinute = tag.BeatsPerMinute; //<--

        //get other metadata about file

        var title = tag.Title;
        var album = tag.Album;
        var genre = tag.JoinedGenres;
        var artists = tag.JoinedPerformers;
        var year = (int)tag.Year;
        var tagTypes = file.TagTypes;

        var properties = file.Properties;
        var pictures = tag.Pictures; //Album art
        var length = properties.Duration.TotalMilliseconds;
        var bitrate = properties.AudioBitrate;
        var samplerate = properties.AudioSampleRate;
    }
}


来源:https://stackoverflow.com/questions/48240574/how-can-i-get-the-bpm-property-of-an-mp3-file-in-a-windows-forms-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!