Convert 3-byte stereo WAV-file to numpy array

后端 未结 3 1526
小蘑菇
小蘑菇 2021-01-13 04:29

I have been given a large WAV-file of continuous underwater recording which I would like to convert to a numpy array for analysis. I am struggling to do this.

So far

3条回答
  •  萌比男神i
    2021-01-13 05:26

    For those with similar issues I post my solution. Note that this converts a 24-bit wave file into a signed floating point numpy array. Leave the /int2float part out when only converting to integers.

    frames = wavfile.readframes(nsamples)
    
    ch1 = np.zeros(nsamples)
    ch2 = np.zeros(nsamples)
    int2float = (2**23)-1
    
    for x in np.arange(int(nsamples)):
        ch1_24bit_sample = frames[x*6:x*6+3]
        ch2_24bit_sample = frames[x*6+3:x*6+6]
        ch1_32bit_sample = bit24_2_32(ch1_24bit_sample)
        ch2_32bit_sample = bit24_2_32(ch2_24bit_sample)
        ch1[x]=struct.unpack('i',ch_32bit_sample)[0]
        ch2[x]=struct.unpack('i',ch_32bit_sample)[0]
        ch1[x]=ch1[x]/int2float
        ch2[x]=ch2[x]/int2float
    
    def bit24_2_32(strbytes):
        if strbytes[2] < '\x80':
           return strbytes+'\x00'
        else:
           return strbytes+'\xff'
    

提交回复
热议问题