How to convert .pcm files to .wav files (scripting)

15,394

You don't actually need a tool for this. The Python standard library comes with the wave module for writing .wav files, and of course raw .pcm files can be just opened as plain binary files, and if you need to do any simple transformations that aren't trivial with a list comprehension, they're trivial with audioop.

For example, this is a complete program from converting stereo 16-bit little-endian 44.1k PCM files to WAV files:

import sys
import wave

for arg in sys.argv[1:]:
    with open(arg, 'rb') as pcmfile:
        pcmdata = pcmfile.read()
    with wave.open(arg+'.wav', 'wb') as wavfile:
        wavfile.setparams((2, 2, 44100, 0, 'NONE', 'NONE'))
        wavfile.writeframes(pcmdata)

In older versions of Python, you may have to use with contextlib.closing(wave.open(…)) (or an explicit open and close instead of a with statement).

Share:
15,394
Buck
Author by

Buck

Updated on July 28, 2022

Comments

  • Buck
    Buck almost 2 years

    I would like to convert .pcm files to .wav files using a tool such as SOX in a Python script. The tool needs to be cross platform compatible (Windows & Linux). Any suggestions?

  • abarnert
    abarnert about 11 years
    @Buck: Oops, yeah. You probably have 16-bit audio, not 128-bit audio. :) Edited the answer.
  • abarnert
    abarnert about 11 years
    @Buck: More importantly… Is your raw PCM stereo 16-bit little-endian 44.1k, or some other format? And, if the latter, do you know how to either specify the same format for WAV or convert to the desired format, or do you need help?
  • Fabien Snauwaert
    Fabien Snauwaert over 5 years
    Note for anyone still using Python 2.7: you'll need to use a wavfile = wave.open( ... ) syntax in place of the second with -- because else it'll fail with a AttributeError: Wave_write instance has no attribute '__exit__' error.