On this page
  1. wave
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Inspecting WAV Metadata and Duration
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

wave

Prev: warnings | Up: stdlib_module | Next: weakref
Rel: colorsys, gettext, locale, turtle, turtledemo
Ref: docs.python.org — wave
Tags: #public #python3 #stdlib


Import

import wave

Overview

Reader and writer for uncompressed PCM WAV audio files (wave.open()). Use wave to inspect audio headers (channels, sample width, frame rate), synthesize simple tones/test fixtures with struct or array, or extract raw PCM samples for DSP work.

Quick Start

import io
import math
import struct
import wave

buf = io.BytesIO()
sample_rate = 8000
with wave.open(buf, "wb") as wf:
    wf.setnchannels(1)       # mono
    wf.setsampwidth(2)       # 16-bit signed PCM
    wf.setframerate(sample_rate)
    frames = b"".join(
        struct.pack("<h", int(16000 * math.sin(2 * math.pi * 440 * i / sample_rate)))
        for i in range(800)  # 0.1 seconds of 440 Hz tone
    )
    wf.writeframes(frames)

buf.seek(0)
with wave.open(buf, "rb") as rf:
    assert (rf.getnchannels(), rf.getsampwidth(), rf.getframerate(), rf.getnframes()) == (1, 2, 8000, 800)

Implementation Walkthrough

1. Inspecting WAV Metadata and Duration

getparams() returns a named tuple (nchannels, sampwidth, framerate, nframes, comptype, compname):

import wave

def wav_duration_seconds(path: str) -> float:
    with wave.open(path, "rb") as wf:
        p = wf.getparams()
        return p.nframes / float(p.framerate)

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes