获取.wav文件长度或持续时间

时间:2011-10-20 09:27:59

标签: python audio

我正在寻找一种方法来查找python中音频文件(.wav)的持续时间。到目前为止,我看了python wave库,mutagenpymediapymad我无法获得wav文件的持续时间。 Pymad给了我持续时间,但不一致。

提前致谢。

10 个答案:

答案 0 :(得分:42)

持续时间等于帧数除以帧速率(每秒帧数):

import wave
import contextlib
fname = '/tmp/test.wav'
with contextlib.closing(wave.open(fname,'r')) as f:
    frames = f.getnframes()
    rate = f.getframerate()
    duration = frames / float(rate)
    print(duration)

关于@edwards的评论,这里有一些产生2通道波形文件的代码:

import math
import wave
import struct
FILENAME = "/tmp/test.wav"
freq = 440.0
data_size = 40000
frate = 1000.0
amp = 64000.0
nchannels = 2
sampwidth = 2
framerate = int(frate)
nframes = data_size
comptype = "NONE"
compname = "not compressed"
data = [(math.sin(2 * math.pi * freq * (x / frate)),
        math.cos(2 * math.pi * freq * (x / frate))) for x in range(data_size)]
try:
    wav_file = wave.open(FILENAME, 'w')
    wav_file.setparams(
        (nchannels, sampwidth, framerate, nframes, comptype, compname))
    for values in data:
        for v in values:
            wav_file.writeframes(struct.pack('h', int(v * amp / 2)))
finally:
    wav_file.close()

如果您在音频播放器中播放结果文件,您会发现持续时间为40秒。如果您运行上面的代码,它还会将持续时间计算为40秒。所以我认为帧数不受通道数量的影响,上面的公式是正确的。

答案 1 :(得分:10)

一种非常简单的方法是使用pysoundfile,https://github.com/bastibe/PySoundFile

以下是一些示例代码:

@Component({
  ...
})
export class ScoreListComponent { ... }

该特定文件的输出为:

import soundfile as sf
f = sf.SoundFile('447c040d.wav')
print('samples = {}'.format(len(f)))
print('sample rate = {}'.format(f.samplerate))
print('seconds = {}'.format(len(f) / f.samplerate))

这与soxi一致:

samples = 232569
sample rate = 16000
seconds = 14.5355625

答案 2 :(得分:6)

我们可以使用ffmpeg来获取任何视频或音频文件的持续时间。

要安装ffmpeg,请按照此link

进行操作
import subprocess
import re

process = subprocess.Popen(['ffmpeg',  '-i', path_of_wav_file], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = process.communicate()
matches = re.search(r"Duration:\s{1}(?P<hours>\d+?):(?P<minutes>\d+?):(?P<seconds>\d+\.\d+?),", stdout, re.DOTALL).groupdict()

print matches['hours']
print matches['minutes']
print matches['seconds']

答案 3 :(得分:4)

import os
path="c:\\windows\\system32\\loopymusic.wav"
f=open(path,"r")

#read the ByteRate field from file (see the Microsoft RIFF WAVE file format)
#https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
#ByteRate is located at the first 28th byte
f.seek(28)
a=f.read(4)

#convert string a into integer/longint value
#a is little endian, so proper conversion is required
byteRate=0
for i in range(4):
    byteRate=byteRate + ord(a[i])*pow(256,i)

#get the file size in bytes
fileSize=os.path.getsize(path)  

#the duration of the data, in milliseconds, is given by
ms=((fileSize-44)*1000)/byteRate

print "File duration in miliseconds : " % ms
print "File duration in H,M,S,mS : " % ms/(3600*1000) % "," % ms/(60*1000) % "," % ms/1000 % "," ms%1000
print "Actual sound data (in bytes) : " % fileSize-44  
f.close()

答案 4 :(得分:2)

要查找音乐文件的长度,可以使用audioread模块,

安装音频读取:pip install audioread

然后使用此代码:

import audioread
with audioread.audio_open(filepath) as f:
    totalsec = f.duration
    min,sec = divmod(totalsec,60) # divides total time in minute  and second 
                                    #and store it in min and sec variable respectively

答案 5 :(得分:1)

librosa库可以执行以下操作:librosa

import librosa
librosa.get_duration(filename='my.wav')

答案 6 :(得分:1)

Let,T为两个连续样本之间的持续时间。因此,我们可以写t = nT或t = n / Fs。

from scipy.io import wavfile
Fs, data = wavfile.read('filename.wav')
n = data.size
t = n / Fs

答案 7 :(得分:1)

我试图获取'.wav'以外的音频文件的不同格式的长度,并且尝试了上述几种解决方案,但对我不起作用

这对我有用:

from pydub.utils import mediainfo
mediainfo('audiofile')['duration']

答案 8 :(得分:1)

pydub 的另一种解决方案:

import pydub
audio_seg = AudioSegment.from_wav('mywav.wav')
total_in_ms = len(audio_seg)

答案 9 :(得分:-1)

这很简短,不需要任何模块,适用于所有操作系统:

import os
os.chdir(foo) # Get into the dir with sound
statbuf = os.stat('Sound.wav')
mbytes = statbuf.st_size / 1024
duration = mbytes / 200
相关问题