Generate WAVE files in pure Python

Everything and anything, but nothing about the LinuxSampler project.
Post Reply
User avatar
dahnielson
Moderator
Posts: 632
Joined: Wed Jan 23, 2008 11:25 pm
Location: Linköping / Tranås, Sweden
Contact:

Generate WAVE files in pure Python

Post by dahnielson » Fri Mar 21, 2008 2:22 pm

Not that it's very difficult using the standard library wave and array modules. So for future reference when you want to experiment with sound generation (like synthesizing IRs):

Code: Select all

"""Output an empty 1 second 16-bit WAVE file."""

import wave
import array

seconds = 1.0
samples_per_second = 44100
number_of_samples = int(samples_per_second * seconds)

sample_array = array.array('h')
for n in xrange(number_of_samples):
    sample_array.append(0)

wave_out = wave.open("outfile.wav", "w")
wave_out.setnchannels(1)
wave_out.setsampwidth(2) # 2 bytes for -32768 to 32767 amplitude
wave_out.setframerate(samples_per_second)
wave_out.setcomptype("NONE", "Uncompressed")
wave_out.writeframes(sample_array.tostring())
wave_out.close()
And if you are using SciPy (which you should) it's even simpler to write an array:

Code: Select all

from scipy.io import wavfile
wavfile.write("outfile.wav", samples_per_second, sample_array)
Finaly, an illustration:

Image
Anders Dahnielson

Ardour2, Qtractor, Linuxsampler, M-AUDIO Delta 1010, Axiom 61, Korg D12, AKAI S2000, E-MU Proteus 2k, Roland R-5, Roland HP 1300e, Zoom RFX-1000, 4GB RAM x86_64 Intel Pentium Dual 1.80GHz Gentoo Linux

Post Reply