如何获取mp3文件的持续时间

3

我尝试了许多方法,但没有得到mp3文件的准确长度值。

使用moviepy:

最初的回答:

audiofile = AudioFileClip(url)
print("duration moviepy: " + str(audiofile.duration))

最初的回答:
我得到了结果:
duration moviepy: 183.59

With mutagen:

from mutagen.mp3 import MP3
audio = MP3(url)
print("duration mutagen: " + str(audio.info.length))

I received another value of duration:

duration mutagen: 140.93416666666667

使用Windows媒体播放器打开文件时的实际持续时间值为:2分49秒。

我不知道我的音频文件发生了什么事情,我测试了一些来自音乐网站的文件,仍然得到了正确的值。 这是我的音频文件

注:Original Answer翻译成“最初的回答”不符合上下文语境,因此未进行翻译。

你分享的音频文件长度为3分钟04秒。 - Primusa
当你下载文件时,它会显示2:49,我不明白发生了什么。 - Hello World
这很奇怪。我现在在想,你的文件中的频率头可能有问题。也许它丢失了,不同的音频库/来源会用不同的默认频率来填补空缺。 - Primusa
所链接的音频文件中大约有1,800个错误,其中一个音频帧后面跟着垃圾数据,这大约占据了整个文件的一半。因此,通过将所有音频帧的持续时间相加计算出的时间应该是文件长度的两倍左右。 - hippietrail
2个回答

1

Using Mutagen

pip install mutagen

Python:

import os
from mutagen.mp3 import MP3

def convert_seconds(seconds):
    hours = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60
    return "%02d:%02d:%02d" % (hours, minutes, seconds)

path = "Your mp3 files floder."
total_length = 0
for root, dirs, files in os.walk(os.path.abspath(path)):
    for file in files:
        if file.endswith(".mp3"):
            audio = MP3(os.path.join(root, file))
            length = audio.info.length
            total_length += length

hours, minutes, seconds = convert_seconds(total_length).split(":")
print("total duration: " + str(int(hours)) + ':' + str(int(minutes)) + ':' + str(int(seconds)))

1

我尝试使用 pysox 处理 包含这个问题帖子的音频文件

注意:pysox 需要 SOX 命令行工具。

使用方法如下:

尝试 pyxsox

import sox
mp3_path = "YOUR STRANGE MP3 FILEPATH"
length = sox.file_info.duration(mp3_path)
print("duration sec: " + str(length))
print("duration min: " + str(int(length/60)) + ':' + str(int(length%60)))

结果是。
duration sec: 205.347982
duration min: 3:25

以及该mp3文件的其他持续时间信息。

ID3 information => 2.49
mutagen => 2:20
pysox => 3:25
actural length => 3:26

mutagen似乎只能读取ID3信息。


奇怪。该文件的ID3标签中没有包含TLETLEN字段,只有一个TSSE字段。因此它告诉我们EncoderSettings = Lavf57.83.100,但对音频的长度或持续时间没有提供任何信息。 - hippietrail

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接