1 min read

Python Wave Module

The wave module provides a convenient interface to the WAV sound format. It does not support compression/decompression, but it does support mono/stereo.

Importing the Module

import wave

Reading WAV Files

To read a WAV file, use wave.open() with mode 'rb'.

import wave

try:
    with wave.open('sample.wav', 'rb') as f:
        print("Channels:", f.getnchannels())
        print("Sample width:", f.getsampwidth())
        print("Frame rate:", f.getframerate())
        print("Number of frames:", f.getnframes())
        print("Parameters:", f.getparams())
except FileNotFoundError:
    print("File not found.")
except wave.Error as e:
    print(f"An error occurred: {e}")

Writing WAV Files

To write a WAV file, use wave.open() with mode 'wb'.

import wave

# Parameters: (nchannels, sampwidth, framerate, nframes, comptype, compname)
nchannels = 1
sampwidth = 2
framerate = 44100

with wave.open('output.wav', 'wb') as f:
    f.setnchannels(nchannels)
    f.setsampwidth(sampwidth)
    f.setframerate(framerate)

    # Write dummy frames (silence)
    # 2 bytes per sample * 1 channel * 100 frames
    data = b'\x00\x00' * 100 
    f.writeframes(data)

programming/python/python