Porównaj commity

...

2 Commity

Autor SHA1 Wiadomość Data
Ewald de Wit dfa02fa5c5 Fix flake8 errors 2022-09-24 09:57:41 +02:00
Ewald de Wit 34050fe2a1 Simplify/optimize read_wav 2022-09-24 09:54:58 +02:00
2 zmienionych plików z 8 dodań i 8 usunięć

Wyświetl plik

@ -85,5 +85,3 @@ class PlayItem:
chunk = self.sound[self.index:idx]
self.index = idx
return chunk

Wyświetl plik

@ -23,7 +23,7 @@ def write_wav(path: str, data: np.ndarray, rate: int, width: int = 4):
rate: Sample rate in Hz.
width: Sample width in bytes.
"""
if not width in [1, 2, 3, 4]:
if width not in [1, 2, 3, 4]:
raise ValueError(f'Invalid sample width: {width}')
data = np.asarray(data)
ch = 1 if len(data.shape) < 2 else len(data)
@ -58,20 +58,22 @@ def read_wav(path: str) -> Sound:
frames = wav.readframes(n)
if width == 4:
buff = np.frombuffer(frames, np.int32)
data = buff.astype('f') / np.float32(2 ** 31 - 1)
norm = 2 ** 31 - 1
elif width == 3:
buff = np.frombuffer(frames, np.uint8)
uints = buff[0::3].astype(np.uint32) << 8 \
| buff[1::3].astype(np.uint32) << 16 \
| buff[2::3].astype(np.uint32) << 24
data = uints.view(np.int32).astype('f') / np.float32(
2 ** 31 - 2 ** 8)
buff = uints.view(np.int32)
norm = 2 ** 31 - 2 ** 8
elif width == 2:
buff = np.frombuffer(frames, np.int16)
data = buff.astype('f') / np.float32(2 ** 15 - 1)
norm = 2 ** 15 - 1
else:
buff = np.frombuffer(frames, np.int8)
data = buff.astype('f') / np.float32(2 ** 7 - 1)
norm = 2 ** 7 - 1
data = buff.astype('f')
data /= np.float32(norm)
data = data.reshape((-1, ch)).T
return Sound(data, rate, width)