Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read the data of a single channel from a stereo wave file in Python

Tags:

python

scipy

wave

I have to read the data from just one channel in a stereo wave file in Python. For this I tried it with scipy.io:

import scipy.io.wavfile as wf
import numpy

def read(path):
    data = wf.read(path)
    for frame in data[1]:
        data = numpy.append(data, frame[0])
    return data

But this code is very slow, especially if I have to work with longer files. So does anybody know a faster way to do this? I thought about the standard wave module by using wave.readframes(), but how are the frames stored there?

like image 451
Richard_Papen Avatar asked Apr 18 '14 12:04

Richard_Papen


1 Answers

scipy.io.wavfile.read returns the tuple (rate, data). If the file is stereo, data is a numpy array with shape (nsamples, 2). To get a specific channel, use a slice of data. For example,

rate, data = wavfile.read(path)
# data0 is the data from channel 0.
data0 = data[:, 0]
like image 143
Warren Weckesser Avatar answered Sep 19 '22 13:09

Warren Weckesser