Skip to content
This repository was archived by the owner on Feb 13, 2020. It is now read-only.

Commit 8772be2

Browse files
committed
Fix util.audioread, now can read 8, 16, 24, 32bits wave files
1 parent 54e4b53 commit 8772be2

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

util.py

+23-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import numpy as np
2+
import wave
23
import scipy.io.wavfile
34

45
def enframe(y, frameSize, overlap):
@@ -15,23 +16,41 @@ def enframe(y, frameSize, overlap):
1516
return out
1617

1718
def audioread(fileName):
18-
fs, au = scipy.io.wavfile.read(fileName)
19-
# conver to float64 and normalize between -1 and 1
19+
#fs, au = scipy.io.wavfile.read(fileName)
20+
audioFile = wave.open(fileName, 'rb')
21+
# get file information and read sample data as string bytes
22+
nChannels, bitPerSample, fs, nFrames = audioFile.getparams()[:4]
23+
strData = audioFile.readframes(nFrames)
24+
audioFile.close()
25+
if bitPerSample > 4:
26+
raise ValueError('Bit per sample can not be greater than 4.')
27+
elif bitPerSample == 4:
28+
au = np.matrix(np.fromstring(strData, dtype=np.int32)/(2**(bitPerSample*8-1)), dtype=np.float64).reshape(-1, nChannels)
29+
elif bitPerSample == 3:
30+
au = np.matrix(np.array([int.from_bytes(strData[i:i+bitPerSample], byteorder='little', signed=True) for i in range(0, len(strData), bitPerSample)], dtype=np.float64)/(2**(bitPerSample*8-1))).reshape(-1, nChannels)
31+
elif bitPerSample == 2:
32+
au = np.matrix(np.fromstring(strData, dtype=np.int16)/(2**(bitPerSample*8-1)), dtype=np.float64).reshape(-1, nChannels)
33+
elif bitPerSample == 1:
34+
au = np.matrix((np.array(np.fromstring(strData, dtype=np.uint8), dtype=np.float64)-128)/(2**(bitPerSample*8-1))).reshape(-1, nChannels)
35+
36+
'''
2037
if au.dtype == 'uint8':
2138
au = np.matrix(au.astype(np.float64) / (2**7)).reshape(au.shape[0], -1)
2239
elif au.dtype == 'int16':
2340
au = np.matrix(au.astype(np.float64) / (2**15)).reshape(au.shape[0], -1)
2441
else:
2542
au = np.matrix(au.astype(np.float64)).reshape(au.shape[0], -1)
26-
return (fs, au)
43+
'''
44+
return (fs, au, bitPerSample)
2745

2846
def main():
2947
import os
3048
fileList = os.listdir('./testAudio/')
3149
for i in fileList:
32-
fs, au = audioread(os.path.join(os.getcwd(), 'testAudio', i))
50+
fs, au, bitPerSample = audioread(os.path.join(os.getcwd(), 'testAudio', i))
3351
print('==========================')
3452
print(i)
53+
print(bitPerSample)
3554
print(au.dtype)
3655
print(au.shape)
3756
print('==========================')

0 commit comments

Comments
 (0)