簡體   English   中英

Get.wav 文件長度或持續時間

[英]Get .wav file length or duration

我正在尋找一種方法來找出 python 中音頻文件 (.wav) 的持續時間。 到目前為止,我已經查看了 python wave庫、 pymedia mutagen pymad ,但我無法獲得 wav 文件的持續時間。 Pymad給了我持續時間,但它並不一致。

持續時間等於幀數除以幀率(每秒幀數):

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 秒。 所以我相信幀數不受通道數的影響,上面的公式是正確的。

librosa 庫可以做到這一點: librosa

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

一個非常簡單的方法是使用音效檔(原pysoundfile )。

以下是有關如何執行此操作的一些示例代碼:

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

該特定文件的輸出是:

samples = 232569
sample rate = 16000
seconds = 14.5355625

這與 soxi 一致:

Input File     : '447c040d.wav'
Channels       : 1
Sample Rate    : 16000
Precision      : 16-bit
Duration       : 00:00:14.54 = 232569 samples ~ 1090.17 CDDA sectors
File Size      : 465k
Bit Rate       : 256k
Sample Encoding: 16-bit Signed Integer PCM

我們可以使用 ffmpeg 來獲取任何視頻或音頻文件的持續時間。

要安裝 ffmpeg,請按照此鏈接

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.decode(), re.DOTALL).groupdict()
 
print(matches['hours'])
print(matches['minutes'])
print(matches['seconds'])
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()

讓,T 是 2 個連續樣本之間的持續時間。 因此,我們可以寫成 t = nT 或 t = n/Fs。

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

要查找音樂文件的長度,可以使用 audioread 模塊,

安裝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

我試圖獲取 '.wav' 以外的不同格式的音頻文件的長度,我嘗試了上面的一些解決方案,但對我不起作用

這對我有用:

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

pydub 的另一個解決方案:

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

計算持續時間(一般),

找到音頻幀的長度並將其除以其采樣率。

例如。 在 Python 中。

如果音頻 = [1,2,3,4,5],其中幀的長度為 5,采樣率 = 44100。

duration = len(audio) / sample_rate

print(duration)

=> 0.00011337868480725624

這是簡短的,不需要模塊,適用於所有操作系統:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM