Skip to content

Instantly share code, notes, and snippets.

@mhdadk
Last active February 16, 2021 07:12
Show Gist options
  • Save mhdadk/2a4f9dda772f280d49531af0d2dd3c58 to your computer and use it in GitHub Desktop.
Save mhdadk/2a4f9dda772f280d49531af0d2dd3c58 to your computer and use it in GitHub Desktop.
Read frames of a WAV file using the wave package in Python
import wave
"""
Generator of frames of byte strings of an audio file.
Arguments:
path (string): .wav file path.
frame_length_sec (float): length of frame in seconds. Common values are in the range [0.01,0.05].
frame_overlap (float): number between 0 (inclusive) and 1 (exclusive) representing the fraction of overlap between consecutive frames. Note
that the generator will get stuck if you input an overlap of 1.
drop_last (boolean): whether to drop the last frame if it is too short compared to the other frames
"""
def read_wav(path,frame_length_sec,frame_overlap,drop_last):
with wave.open(path, 'rb') as fp:
sample_rate = fp.getframerate()
num_frames = fp.getnframes()
frame_length_samples = int(sample_rate * frame_length_sec)
# while the current position of the file pointer is less than the total number of samples in the file
while fp.tell() < num_frames:
yield fp.readframes(frame_length_samples)
# drop last frame if it is too short
if num_frames - fp.tell() < frame_length_samples and drop_last:
break
# move the file pointer back to overlap with the last frame
fp.setpos(fp.tell() - int(frame_overlap * frame_length_samples))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment