Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get .wav file length or duration

Tags:

python

audio

I'm looking for a way to find out the duration of a audio file (.wav) in python. So far i had a look at python wave library, mutagen, pymedia, pymad i was not able to get the duration of the wav file. Pymad gave me the duration but its not consistent.

Thanks in advance.

like image 894
Pannu Avatar asked Oct 20 '11 09:10

Pannu


People also ask

Can WAV files have timecode?

Yes, but if you're asking for timecode-as-audio, that's a different thing. If you export a WAV file, it will take on the timecode of the sequence it is in (but that is metadata, not an actual rattling audio track).

How do I find the length of an audio file?

To determine the file size of an audio file, we have to multiply the bit rate of the audio by its duration in seconds. As a result, we get file size values in terms of kilobits and megabits.

Does WAV have metadata?

FLAC, AIFF and MP3 formats take full advantage of metadata whereas WAV files only allow a little metadata input, so not as helpful for browsing your library. It's important if you want to locate and play music around your home. Network players like our CXN use metadata to browse and play your music.


2 Answers

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

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) 

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

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

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.

like image 150
unutbu Avatar answered Sep 21 '22 03:09

unutbu


the librosa library can do this: librosa

import librosa librosa.get_duration(filename='my.wav') 
like image 39
Max Avatar answered Sep 24 '22 03:09

Max