Faster way to convert from 24 bit wav pcm format t

2019-02-26 18:21发布

I need to read data in from a wav file in 24 bit pcm format, and convert to float. I'm using Python 2.7.2.

The wave package reads the data in as a string, so what I've tried is:

import wave
import numpy as np
import array
import struct

f = wave.open('filename.wav')
# read in entire wav file
wdata = f.readframes(nFrames) 
f.close()

# unpack into signed integers and convert to float      
data = array.array('f')
for i in range(0,nFrames*3,3):
    data.append(float(struct.unpack('<i', '\x00'+ wdata[i:i+3])[0]))

# normalize sample values
data = np.array(data)
data = data / 0x800000

This is quite a bit faster than my earlier approaches, but still quite slow. Can anyone suggest a more efficient method?

标签: python wav pcm
1条回答
forever°为你锁心
2楼-- · 2019-02-26 18:58

This seems to be quite fast, it handles 24-bit values, and it does the normalization:

from scikits.audiolab import Sndfile
import numpy as np

f = Sndfile(fname, 'r')
data = np.array(f.read_frames(f.nframes), dtype=np.float64)
f.close()
return data
查看更多
登录 后发表回答