用Python获取MP3文件句柄的长度

问题描述 投票:2回答:2

我正在写一个Python程序。我需要一些东西来获取一个MP3文件的(音频)长度(最好是以秒为单位),但问题是它是一个开放的文件句柄(A requests 确切地说,是原始请求)。) 我可以把句柄保存到一个临时文件中,然后从那里读取,但我想知道是否有更好的方法。(我必须处理很多文件,不想把它们都保存起来)

python mp3 python-requests
2个回答
1
投票

如果你想从你的 response.content 使用以下代码。

import wave

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

print duration

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)  

print duration

0
投票

当你说 "长度 "时 你是指音频播放时间还是文件的物理大小?文件的长度可以通过检查 "内容-长度 "获得。

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

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

EDIT: 首先安装 sox 用apt或synaptic(sox--Sound eXchange)打包,然后代码如下。

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 懂得。

© www.soinside.com 2019 - 2024. All rights reserved.