'Get length of wav file in samples with python
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?
Solution 1:[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:[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:[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)
Solution 4:[4]
You can simply use the scipy library. Try this:
from scipy.io.wavfile import read
audiofile = '/path/to/file.wav'
sample_rate_in_s, data = read(audiofile)
print(len(data))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Will |
| Solution 3 | Taufiq Rahman |
| Solution 4 | Patrick von Platen |
