changeset 0:a8cde97eae7b

Initialise with test files and simple audio-file reading code
author Chris Cannam
date Wed, 03 Oct 2012 11:54:18 +0100
parents
children 97232ecb4aa8
files audiofile.py test_audiofile.py testfiles/120bpm.wav testfiles/4sample-stereo-ny.wav
diffstat 4 files changed, 34 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /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())
+
--- /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
+
Binary file testfiles/120bpm.wav has changed
Binary file testfiles/4sample-stereo-ny.wav has changed