view audiofile.py @ 5:ea2387fd1b90 tip

Add CC0 disclaimers
author Chris Cannam
date Thu, 04 Oct 2012 22:12:02 +0100
parents a8cde97eae7b
children
line wrap: on
line source

# To the extent possible under law, Chris Cannam and QMUL have waived
# all copyright and related or neighboring rights to this file
# (http://creativecommons.org/about/cc0)

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())