Mercurial > hg > python-tutorial-skeleton
comparison 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 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:a8cde97eae7b |
---|---|
1 | |
2 import wave | |
3 import numpy as np | |
4 | |
5 def decode_to_mono_samples(rawdata, n_channels): | |
6 """Given raw PCM16 interleaved WAV-format audio data as a binary | |
7 string, decode and return as floating-point samples in range [-1,1)""" | |
8 samples = np.fromstring(rawdata, 'Int16').astype(float) | |
9 samples = samples / 32768 | |
10 totals = sum(samples[c::n_channels] for c in range(0, n_channels)) | |
11 return totals / n_channels | |
12 | |
13 def read_all_mono_samples_from_file(filename): | |
14 """Read the whole of the given PCM16 WAV-format given audio file, | |
15 mix down to mono by taking means across channels, and return as an | |
16 array of floating-point sampless in range [-1,1)""" | |
17 wavfile = wave.open(filename, 'r') | |
18 n_channels = wavfile.getnchannels() | |
19 rawdata = wavfile.readframes(-1) # read all data | |
20 decoded = decode_to_mono_samples(rawdata, n_channels) | |
21 return (decoded, wavfile.getframerate()) | |
22 |