Windows系统下如何借助os模块获取音频文件(如MP3)时长?
在Windows下用Python获取音频文件时长的方法
os.stat()只能获取文件的系统属性(比如大小、修改时间),拿不到媒体文件的元数据(比如音频时长)。要获取Windows系统中已存储的音频时长,有几个实用的方案:
方法1:用mutagen库解析音频元数据
mutagen是专门处理音频元数据的Python库,支持MP3、FLAC等多种格式,不需要依赖系统API,跨平台也能用。
首先安装库:
pip install mutagen
示例代码(获取MP3时长):
from mutagen.mp3 import MP3 audio_path = r"C:\example\test.mp3" audio = MP3(audio_path) # 获取时长,单位为秒,可转成时分秒格式 duration_seconds = audio.info.length minutes = int(duration_seconds // 60) seconds = int(duration_seconds % 60) print(f"音频时长:{minutes}分{seconds}秒")
方法2:调用Windows系统属性(用pywin32)
如果想直接读取Windows文件属性里存储的时长(就是右键文件→属性→详细信息里的“时长”),可以用pywin32库调用Windows Shell API。
安装库:
pip install pywin32
示例代码:
import win32com.client def get_audio_duration_win(file_path): shell = win32com.client.Dispatch("Shell.Application") folder = shell.NameSpace(file_path.rsplit("\\", 1)[0]) file_item = folder.ParseName(file_path.rsplit("\\", 1)[1]) # 38是Windows Shell属性中“时长”对应的常见索引值 duration_str = folder.GetDetailsOf(file_item, 38) return duration_str # 测试 audio_path = r"C:\example\test.mp3" print(f"音频时长:{get_audio_duration_win(audio_path)}")
注意:不同Windows版本的属性索引可能有变化,若返回空值,可以尝试从0开始遍历所有属性值,找到对应“时长”的索引。
方法3:用ffmpeg命令行工具
如果你已经安装了ffmpeg,可以通过subprocess调用命令行获取时长,适合批量处理场景。
示例代码:
import subprocess def get_duration_with_ffmpeg(file_path): cmd = [ "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file_path ] result = subprocess.run(cmd, capture_output=True, text=True) duration_seconds = float(result.stdout.strip()) minutes = int(duration_seconds // 60) seconds = int(duration_seconds % 60) return f"{minutes}分{seconds}秒" # 测试 audio_path = r"C:\example\test.mp3" print(f"音频时长:{get_duration_with_ffmpeg(audio_path)}")
前提是ffmpeg已添加到系统环境变量,或者在代码中指定ffprobe的完整路径。
内容的提问来源于stack exchange,提问作者user22364178
相关产品推荐
相关产品推荐

