Generate pure tones using Python.
Pure tones contain energy at exactly one frequency. This is why frequency spectra for pure tones are sometimes called line spectra. A pure tone can be characterized by its frequency, amplitude, and phase.
This script generates a pure tone at a given level, sampling rate, duration, and frequency. Signal parameters can be adjusted as needed.
# import libraries
import pyaudio
import numpy as np
from matplotlib import pyplot as plt
from scipy.io.wavfile import write
= pyaudio.PyAudio()
p
# define signal parameters
= -10 # magnitude, range = [-74, 0], so when mag = 0, A = 1
mag_in_dB # ydb = 20 log10(y), where y = mag; y is I1/I2
= 10.0 ** ((mag_in_dB)/20.0) #convert mag_in_dB to mag, so volume = mag, range = [-1,1]
amplitude = 44100 # sampling rate, Hz, must be integer
fs = 1 # in seconds, may be float
duration = 1000 # sine frequency, Hz, may be float
f
# generate range of samples
= np.arange(fs*duration)*(f/fs)
sig_sample # take sine wave of generated samples and convert to float32 array
= (np.sin(2*np.pi*sig_sample)).astype(np.float32)
samples
# listen to the samples
= p.open(format=pyaudio.paFloat32,
stream =1,
channels=fs,
rate=True)
output
stream.stop_stream()
stream.close()
p.terminate()
# plot signal
plt.plot(samples)'signal')
plt.title(
plt.show()
# write samples to .wav file
'tone.wav', fs, samples*amplitude) write(