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.
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).
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.
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.
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.
the librosa library can do this: librosa
import librosa librosa.get_duration(filename='my.wav')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With