在 Python 中获取 MP3 文件句柄的长度

Get length of MP3 file handle in Python

我正在编写 Python 程序。我需要一些东西来获取 MP3 文件的(音频)长度(最好以秒为单位),但要注意的是它是一个打开的文件句柄(准确地说是 requests 原始请求)。我可以将句柄保存到一个临时文件并从那里读取它,但我想知道是否有更好的方法。 (我要处理很多文件,不想全部保存)

在下面的示例中,我们读取本地文件以获取音频时长:

import wave

info = wave.open('test.wav', 'r')
frames = info.getnframes()
rate = info.getframerate()

duration = frames / float(rate)  

您可以使用 io.BytesIOresponse.content 获取文件对象:

import wave
import io
import requests


url = "http://localhost/test.wav"
r = requests.get(url)
#To get a file like object from r.content we use "io.BytesIO"
infofile = wave.open(io.BytesIO(r.content), 'r')
frames = infofile.getnframes()
rate = infofile.getframerate()

duration = frames / float(rate)  

当你说 "length" 时,你指的是音频播放时间还是文件的物理大小?
文件的长度可通过检查 'content-length':

获得
>>> import requests
>>> r = requests.get('http://localhost/postcard/vp1.mp3', stream=True)
>>> print r.headers
CaseInsensitiveDict({'content-length': '3119672', 'accept-ranges': 'bytes', 'server': 'Apache/2.4.7 (Ubuntu)', 'last-modified': 'Fri, 19 Jun 2015 13:18:08 GMT', 'etag': '"2f9a38-518dec14f8cf5"', 'date': 'Sun, 22 Nov 2015 10:20:07 GMT', 'content-type': 'audio/mpeg'})

关于音频长度,我怀疑您必须先下载文件才能确定其 运行 时间。

编辑:
首先使用 apt 或 synaptic (sox - Sound eXchange)
安装 sox 软件包 那么代码如下:

import os, requests
url = "http://localhost/postcard/vp1.mp3"
pre,suff = url.rsplit('.')
r = requests.get(url)
with open('/tmp/tmp.'+suff, 'wb') as f:
    for chunk in r.iter_content(1024000):
        f.write(chunk)
stats=os.popen('soxi /tmp/tmp.'+suff).readlines()
for info in stats:
    print info.strip()

输出:

Input File     : '/tmp/tmp.mp3'
Channels       : 2
Sample Rate    : 44100
Precision      : 16-bit
Duration       : 00:02:57.08 = 7809404 samples = 13281.3 CDDA sectors
File Size      : 3.12M
Bit Rate       : 141k
Sample Encoding: MPEG audio (layer I, II or III)
Comments       :
Title=Smoke Gets in Your Eyes
Artist=Bryan Ferry
Album=More Than This: The Best of Bryan Ferry + Roxy Music
Tracknumber=6/20
Discnumber=1

使用 soxi 是作弊,但我还没来得及安装可能会起作用的 pysox 包。
这不仅适用于 wav 文件,而且适用于 sox 理解的所有音频类型。