~vijaykumar

[ Home | Feed | Twitter | Vector Art | Ascii Art | Tutorials ]

Processing .WAV files in Python

Wed, 06 May 2009

The wave Python module can be used to read and write .WAV files. Unfortunately, the manual is not very clear. Here is a short tutorial on how to use the wave module.

The wave module provides two objects for handling .WAV files.

  1. Wave_read object, for reading .WAV files

  2. Wave_write object, for writing .WAV files

Both the objects are returned by the wave module’s factory method open(). The mode argument passed to open() decides which of the two objects is returned.

#!/usr/bin/env python

import wave # 1
import struct

ifile = wave.open("input.wav")
ofile = wave.open("output.wav", "w")
ofile.setparams(ifile.getparams())

sampwidth = ifile.getsampwidth()
fmts = (None, "=B", "=h", None, "=l")
fmt = fmts[sampwidth]
dcs  = (None, 128, 0, None, 0)
dc = dcs[sampwidth]

for i in range(ifile.getnframes()):
    iframe = ifile.readframes(1)

    iframe = struct.unpack(fmt, iframe)[0]
    iframe -= dc

    oframe = iframe / 2;

    oframe += dc
    oframe = struct.pack(fmt, oframe)
    ofile.writeframes(oframe)

ifile.close()
ofile.close()

Permalink | Add Comment | Share: Twitter, Facebook, Buzz, ... | Tags: python

blog comments powered by Disqus

Powered by Python | Made with PyBlosxom | Valid XHTML 1.1 | Best Viewed With Any Browser | Icon Credits | CC-BY-SA