Get length of wav file in samples with python
16,063
Solution 1
If you are using scipy you can get the length in seconds using scipy.io
import scipy.io.wavfile as wav
file_path = "/path/to/yourfile.wav"
(source_rate, source_sig) = wav.read(file_path)
duration_seconds = len(source_sig) / float(source_rate)
If you are using pydub
you can simply read the audio segment and get duration.
from pydub import AudioSegment
audio = AudioSegment.from_file(file_path)
print(audio.duration_seconds)
Solution 2
os.path.getsize
will get the size of files in bytes.
>>> import os
>>> b = os.path.getsize('C:\\Users\\Me\\Desktop\\negley.wav')
>>> b
31449644 #This is in bytes, in megabytes it would be 31.45 Megabytes (which is accurate)
Want to get the size in megabytes?
>>> b = int(os.path.getsize('C:\\Users\\Will\\Desktop\\negley.wav')) / 1024 / 1024
>>> b
29.992717742919922 #Close enough?
Or to get the length in seconds, you can use Achilles method of:
import wave
import contextlib
audiofile = 'C:\\Users\\Will\\Desktop\\negley.wav'
with contextlib.closing(wave.open(audiofile,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
length = frames / float(rate)
print(length)
Solution 3
The length of an audio or wave file is determined by it's framerate.To get the length try this:
import wave
import contextlib
audiofile = '/pathto/your.wav'
with contextlib.closing(wave.open(audiofile,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
length = frames / float(rate)
print(length)
Author by
L.Kom
Updated on June 23, 2022Comments
-
L.Kom about 2 years
i am trying to run a python code that processes wav files. It asks to give length of file in samples. After research i found this command
>>>import os >>>b=os.path.getsize('/somepath') >>>b
but i am not sure if it gives result in samples.
Anyone can help?