Get .wav file length or duration Get .wav file length or duration python python

Get .wav file length or duration


The duration is equal to the number of frames divided by the framerate (frames per second):

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

Regarding @edwards' comment, here is some code to produce a 2-channel wave file:

import mathimport waveimport structFILENAME = "/tmp/test.wav"freq = 440.0data_size = 40000frate = 1000.0amp = 64000.0nchannels = 2sampwidth = 2framerate = int(frate)nframes = data_sizecomptype = "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()

If you play the resultant file in an audio player, you'll find that is 40 seconds in duration. If you run the code above it also computes the duration to be 40 seconds. So I believe the number of frames is not influenced by the number of channels and the formula above is correct.


the librosa library can do this: librosa

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


A very simple method is to use soundfile (formerly pysoundfile).

Here's some example code of how to do this:

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

The output for that particular file is:

samples = 232569sample rate = 16000seconds = 14.5355625

This aligns with soxi:

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