annotate audiofile.py @ 5:ea2387fd1b90 tip

Add CC0 disclaimers
author Chris Cannam
date Thu, 04 Oct 2012 22:12:02 +0100
parents a8cde97eae7b
children
rev   line source
Chris@5 1
Chris@5 2 # To the extent possible under law, Chris Cannam and QMUL have waived
Chris@5 3 # all copyright and related or neighboring rights to this file
Chris@5 4 # (http://creativecommons.org/about/cc0)
Chris@0 5
Chris@0 6 import wave
Chris@0 7 import numpy as np
Chris@0 8
Chris@0 9 def decode_to_mono_samples(rawdata, n_channels):
Chris@0 10 """Given raw PCM16 interleaved WAV-format audio data as a binary
Chris@0 11 string, decode and return as floating-point samples in range [-1,1)"""
Chris@0 12 samples = np.fromstring(rawdata, 'Int16').astype(float)
Chris@0 13 samples = samples / 32768
Chris@0 14 totals = sum(samples[c::n_channels] for c in range(0, n_channels))
Chris@0 15 return totals / n_channels
Chris@0 16
Chris@0 17 def read_all_mono_samples_from_file(filename):
Chris@0 18 """Read the whole of the given PCM16 WAV-format given audio file,
Chris@0 19 mix down to mono by taking means across channels, and return as an
Chris@0 20 array of floating-point sampless in range [-1,1)"""
Chris@0 21 wavfile = wave.open(filename, 'r')
Chris@0 22 n_channels = wavfile.getnchannels()
Chris@0 23 rawdata = wavfile.readframes(-1) # read all data
Chris@0 24 decoded = decode_to_mono_samples(rawdata, n_channels)
Chris@0 25 return (decoded, wavfile.getframerate())
Chris@0 26