annotate audiofile.py @ 3:4be70944d21b
skeleton_v2
Add some basic signal processing methods we need
author |
Chris Cannam |
date |
Thu, 04 Oct 2012 17:14:05 +0100 |
parents |
a8cde97eae7b |
children |
ea2387fd1b90 |
rev |
line source |
Chris@0
|
1
|
Chris@0
|
2 import wave
|
Chris@0
|
3 import numpy as np
|
Chris@0
|
4
|
Chris@0
|
5 def decode_to_mono_samples(rawdata, n_channels):
|
Chris@0
|
6 """Given raw PCM16 interleaved WAV-format audio data as a binary
|
Chris@0
|
7 string, decode and return as floating-point samples in range [-1,1)"""
|
Chris@0
|
8 samples = np.fromstring(rawdata, 'Int16').astype(float)
|
Chris@0
|
9 samples = samples / 32768
|
Chris@0
|
10 totals = sum(samples[c::n_channels] for c in range(0, n_channels))
|
Chris@0
|
11 return totals / n_channels
|
Chris@0
|
12
|
Chris@0
|
13 def read_all_mono_samples_from_file(filename):
|
Chris@0
|
14 """Read the whole of the given PCM16 WAV-format given audio file,
|
Chris@0
|
15 mix down to mono by taking means across channels, and return as an
|
Chris@0
|
16 array of floating-point sampless in range [-1,1)"""
|
Chris@0
|
17 wavfile = wave.open(filename, 'r')
|
Chris@0
|
18 n_channels = wavfile.getnchannels()
|
Chris@0
|
19 rawdata = wavfile.readframes(-1) # read all data
|
Chris@0
|
20 decoded = decode_to_mono_samples(rawdata, n_channels)
|
Chris@0
|
21 return (decoded, wavfile.getframerate())
|
Chris@0
|
22
|