如何在Windows Forms应用中获取MP3文件的BPM属性?
在Windows Forms中读取MP3的BPM属性
嘿,我刚好折腾过类似的需求,知道Windows Forms没法用UWP那套Windows.Storage API,给你两个靠谱的方案搞定这个问题:
方案一:用原生Windows Shell API(不用装第三方库)
Windows自带的Shell组件可以读取文件的各种扩展属性,BPM就在里面。操作步骤很简单:
- 先在你的Windows Forms项目里添加COM引用:找到
Microsoft Shell Controls And Automation并勾选它 - 然后用下面的代码读取BPM:
using Shell32; using System.IO; public static double? GetMp3Bpm(string filePath) { var shell = new Shell(); var folder = shell.NameSpace(Path.GetDirectoryName(filePath)); var fileItem = folder.ParseName(Path.GetFileName(filePath)); // 注意:BPM对应的属性索引通常是248,但不同Windows版本/区域可能有差异 string bpmText = folder.GetDetailsOf(fileItem, 248); if (double.TryParse(bpmText, out double bpm)) { return bpm; } return null; }
小提示:如果248不对,你可以写个循环遍历
folder.GetDetailsOf(null, index),找到显示“BPM”或“节拍数/分钟”的那个索引值,替换进去就行。
方案二:用免费开源的TagLibSharp库(更省心)
如果不想折腾原生API的索引问题,TagLibSharp绝对是首选——这是个成熟的音频标签处理库,支持几乎所有常见音频格式,完全兼容Windows Forms。
- 打开NuGet包管理器,搜索并安装
TagLibSharp - 然后用几行代码就能搞定:
using TagLib; public static double? GetMp3Bpm(string filePath) { using var audioFile = TagLib.File.Create(filePath); if (audioFile.Tag != null && audioFile.Tag.BeatsPerMinute > 0) { return audioFile.Tag.BeatsPerMinute; } return null; }
这个方案更稳定,不用操心系统差异,还能顺便处理其他音频标签,推荐优先用这个。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

