简体   繁体   中英

Python wave: Extracting stereo channels separately from *.wav-file

I have a 32 bit *.wav-file 44100Hz sampling. I use use wave and python struct.unpack to get the data to an array. However I want to get each of the two stereo channels as a separate array. How do I do this as simply as possible? This is the code I have:

def read_values(filename):
    wave_file = open(filename, 'r')
    nframes = wave_file.getnframes()
    nchannels = wave_file.getnchannels()
    sampling_frequency = wave_file.getframerate()
    T = nframes / float(sampling_frequency)
    read_frames = wave_file.readframes(nframes)
    wave_file.close()
    data = unpack("%dh" %  nchannels*nframes, read_frames)
    return T, data, nframes, nchannels, sampling_frequency

Are you able to (1) modify the code such that it returns two arrays, one for each channel, and (2) explain how the wave is structured, and how the functions which I used incorrectly is used correctly.

Left and right channel in stereo files are interleaved. You can find lots of information about this online, eg look at the figures here .

So if you already have your whole audio data in an list, you just have to get very 2nd sample for stereo, every 4th sample for quadro, etc. You can do this with list splicing:

data_per_channel = [data[offset::nchannels] for offset in range(nchannels)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM