Generate white noise using Python.
White noise is characterized by a flat frequency spectrum. A white noise signal that is infinitely long, in theory, will have equal energy at each frequency.
This script generates a white noise signal at a given sampling rate, low cutoff frequency, high cutoff frequency, and duration. Signal parameters can be adjusted as needed.
import pyaudio
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter
from scipy.io.wavfile import write
from scipy import fft, arange
# sample rate and desired cutoff frequencies (in Hz)
= 44100
fs = 900
lowcut = 1100
highcut
= 0
mean = 1
std =10 # duration in s
duration= fs*duration #44100 == 1s
num_samples
def butter_bandpass(lowcut, highcut, fs, order=5):
= 0.5 * fs
nyq = lowcut / nyq
low = highcut / nyq
high = butter(order, [low, high], btype='band')
b, a return b, a
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
= butter_bandpass(lowcut, highcut, fs, order=order)
b, a = lfilter(b, a, data)
y return y
def generateAudioStimulus():
= pyaudio.PyAudio()
p = np.random.normal(mean, std, size=num_samples)
noise = butter_bandpass_filter(noise, lowcut, highcut, fs)
filtered_noise = filtered_noise.astype(np.float32).tobytes()
samples
# for paFloat32 sample values must be in range [-1.0, 1.0]
= p.open(format=pyaudio.paFloat32, channels=1, rate=fs, output=True)
stream
# write array as .wav
'white.wav', fs, filtered_noise)
write(
# listen to the sound
stream.write(samples)
stream.stop_stream()
stream.close()
p.terminate()
# plot
= np.linspace(0, duration, num_samples, endpoint=False)
t =f'cutoffs: low={lowcut}Hz, high={highcut}Hz')
plt.plot(t, filtered_noise, label'time (seconds)')
plt.xlabel(-.02, .02], 0, 1/fs, linestyles='--')
plt.hlines([True)
plt.grid('tight')
plt.axis(='upper left')
plt.legend(loc
plt.show()
generateAudioStimulus()