Read/write of "wav" audio files using the scipy.io.wavfile module.
In the python program, audio tracks = numpy arrays.
import numpy as np
from scipy.io.wavfile import read as wavread
from scipy.io.wavfile import write as wavwrite
Writing
Example for a 2 seconds pure 400 Hz sine wave.
samplerate = 44100
freq = 440
seconds = 2
time = np.linspace(0., seconds, seconds*samplerate, endpoint=False)
signal = np.sin(2*np.pi*freq*time)
# The final amplitude should span the signed 16-bit integers range [-2**15,2**15)
amplitude = np.iinfo(np.int16).max # iinfo returns the range for the int16 type, then max resolves to -> 2**15
data = amplitude * signal
wavwrite("simple440.wav", samplerate, data.astype(np.int16))
Reading
rate, data = wavread('simple440.wav')
print('rate:',rate,'Hz')
print('data is a:',type(data))
print('data shape is:', data.shape)
Plot
import matplotlib.pyplot as plt
plt.subplots(dpi=100)
plt.plot(time[:200]*1000, data[:200])
plt.xlabel('milliseconds')
plt.ylabel('signed 16-bit integers')
plt.show()
Playing the file
Using the simpleaudio module to play the file
import simpleaudio as sa
# Start playback and wait for playback to finish before exiting
play_obj = sa.play_buffer(data, 1, 2, 44100)
play_obj.wait_done()
import numpy as np
import matplotlib.pyplot as plt
from scipy.io.wavfile import write as wavwrite
from scipy.io.wavfile import read as wavread
waveform = np.loadtxt('out.dat')
plt.subplots(figsize=(10,3),dpi=100)
plt.plot(waveform, lw=1, c='k')
plt.show()
Data have to be rescaled to a 16 bit range -2^15, 2^15, they will intepreted as -1,1 volt input in LTspice.
data = waveform/waveform.max() * 2**15-1
wavwrite("sipm_data.wav", int(1e9), data.astype(np.int16))
# copy to LTspice directory
# !cp sipm_data.wav /home/valerio/Documents/LTspiceXVII/.
Here it comes the LTspice simulation of a low-pass filter, see Wav files and LTSPICE
# copying back the result
#!cp /home/valerio/Documents/LTspiceXVII/sipm_data_out.wav .
rate, data_out = wavread('sipm_data_out.wav')
print('rate:',rate,'Hz')
print('data is a:',type(data_out))
print('data shape is:', data_out.shape)
# plot rescaled data for comparison
plt.subplots(figsize=(10,3),dpi=100)
plt.plot(data, lw=1,color='k', label='Original waveform')
plt.plot(data_out, lw=1, color='r',label='Filtered waveform')
plt.legend()
plt.show()