diff audiofile.py @ 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 ea2387fd1b90
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())
+