Wav files and Python

Read/write of "wav" audio files using the scipy.io.wavfile module.

In the python program, audio tracks = numpy arrays.

In [1]:
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.

In [2]:
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

In [3]:
rate, data = wavread('simple440.wav')
print('rate:',rate,'Hz')
print('data is a:',type(data))
print('data shape is:', data.shape)
rate: 44100 Hz
data is a: <class 'numpy.ndarray'>
data shape is: (88200,)

Plot

In [4]:
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

In [5]:
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()

Wav files for (non audio) waveform and LTspice

In [6]:
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.

In [7]:
data = waveform/waveform.max() * 2**15-1
wavwrite("sipm_data.wav", int(1e9), data.astype(np.int16))
In [8]:
# 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

In [9]:
# copying back the result
#!cp /home/valerio/Documents/LTspiceXVII/sipm_data_out.wav .
In [10]:
rate, data_out = wavread('sipm_data_out.wav')
In [11]:
print('rate:',rate,'Hz')
print('data is a:',type(data_out))
print('data shape is:', data_out.shape)
rate: 1000000000 Hz
data is a: <class 'numpy.ndarray'>
data shape is: (1600,)
In [12]:
# 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()