dsp/lib/wav.py

44 lines
1.2 KiB
Python
Raw Normal View History

2015-10-18 23:06:39 -07:00
import numpy as np
2015-10-27 04:04:29 -07:00
from .util import lament, count_channels
2015-10-18 23:06:39 -07:00
2017-09-21 04:04:22 -07:00
2015-10-18 23:06:39 -07:00
def wav_smart_read(fn):
2015-10-18 23:33:46 -07:00
lament('wav_smart_read(): DEPRECATED; use wav_read instead.')
2017-09-21 04:04:22 -07:00
# don't use this, it fails to load good files.
import scipy.io.wavfile as wav
2015-10-18 23:06:39 -07:00
srate, s = wav.read(fn)
if s.dtype != np.float64:
bits = s.dtype.itemsize*8
s = np.asfarray(s)/2**(bits - 1)
return srate, s
2017-09-21 04:04:22 -07:00
2015-10-18 23:06:39 -07:00
def wav_smart_write(fn, srate, s):
2016-07-03 04:04:48 -07:00
lament('wav_smart_write(): DEPRECATED; use wav_write instead.')
2017-03-22 04:04:21 -07:00
import scipy.io.wavfile as wav
2015-10-18 23:06:39 -07:00
si = np.zeros_like(s, dtype='int16')
bits = si.dtype.itemsize*8
si += np.clip(s*2**(bits - 1), -32768, 32767)
wav.write(fn, srate, si)
2017-09-21 04:04:22 -07:00
2015-10-18 23:06:39 -07:00
def wav_read(fn):
2017-03-22 04:04:21 -07:00
import ewave
2015-10-18 23:06:39 -07:00
with ewave.open(fn) as f:
s = f.read()
srate = f.sampling_rate
if s.dtype == np.float32:
s = np.asfarray(s)
elif s.dtype != np.float64:
bits = s.dtype.itemsize*8
s = np.asfarray(s)/2**(bits - 1)
return s, srate
2015-10-27 04:04:29 -07:00
2017-09-21 04:04:22 -07:00
2015-10-27 04:04:29 -07:00
def wav_write(fn, s, srate, dtype='h'):
2017-03-22 04:04:21 -07:00
import ewave
2015-10-27 04:04:29 -07:00
if dtype in ('b', 'h', 'i', 'l') and np.max(np.abs(s)) > 1:
lament('wav_write(): WARNING; clipping')
with ewave.open(fn, 'w', srate, dtype, count_channels(s)) as f:
f.write(s)