# HG changeset patch # User Chris Cannam # Date 1349261658 -3600 # Node ID a8cde97eae7bfb76ce9d9c9966ea900ae6b7afb1 Initialise with test files and simple audio-file reading code diff -r 000000000000 -r a8cde97eae7b audiofile.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/audiofile.py Wed Oct 03 11:54:18 2012 +0100 @@ -0,0 +1,22 @@ + +import wave +import numpy as np + +def decode_to_mono_samples(rawdata, n_channels): + """Given raw PCM16 interleaved WAV-format audio data as a binary + string, decode and return as floating-point samples in range [-1,1)""" + samples = np.fromstring(rawdata, 'Int16').astype(float) + samples = samples / 32768 + totals = sum(samples[c::n_channels] for c in range(0, n_channels)) + return totals / n_channels + +def read_all_mono_samples_from_file(filename): + """Read the whole of the given PCM16 WAV-format given audio file, + mix down to mono by taking means across channels, and return as an + array of floating-point sampless in range [-1,1)""" + wavfile = wave.open(filename, 'r') + n_channels = wavfile.getnchannels() + rawdata = wavfile.readframes(-1) # read all data + decoded = decode_to_mono_samples(rawdata, n_channels) + return (decoded, wavfile.getframerate()) + diff -r 000000000000 -r a8cde97eae7b test_audiofile.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test_audiofile.py Wed Oct 03 11:54:18 2012 +0100 @@ -0,0 +1,12 @@ + +import audiofile as af + +def test_read_all_mono_from_file(): + (samples, samplerate) = af.read_all_mono_samples_from_file('testfiles/4sample-stereo-ny.wav') + assert samplerate == 44100 + assert len(samples) == 4 + assert samples[0] > 0.999 and samples[0] < 1 + assert samples[1] == -1 + assert samples[2] > 0.999 and samples[2] < 1 + assert samples[3] == -1 + diff -r 000000000000 -r a8cde97eae7b testfiles/120bpm.wav Binary file testfiles/120bpm.wav has changed diff -r 000000000000 -r a8cde97eae7b testfiles/4sample-stereo-ny.wav Binary file testfiles/4sample-stereo-ny.wav has changed