Skip to content

Instantly share code, notes, and snippets.

@hdf
Created April 1, 2020 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hdf/9b244f74b211b51c77d81cc77bdbcee1 to your computer and use it in GitHub Desktop.
Save hdf/9b244f74b211b51c77d81cc77bdbcee1 to your computer and use it in GitHub Desktop.
Waveform generation example
import pyaudio
import numpy as np
from scipy import signal as sg
from scipy.io.wavfile import write
p = pyaudio.PyAudio()
volume = 1.0 # range [0.0, 1.0]
fs = 44100 # sampling rate, Hz, must be integer
duration = 1.0 # in seconds, may be float
f = 440.0 # sine frequency, Hz, may be float
samples = np.sin(2*np.pi*np.arange(fs*duration)*f/fs).astype(np.float32) # sine wave
samples2 = sg.square(2*np.pi*np.arange(fs*duration)*f/fs).astype(np.float32) # square wave
samples3 = sg.sawtooth(2*np.pi*np.arange(fs*duration)*f/fs).astype(np.float32) # sawtooth wave
samples4 = sg.chirp(np.linspace(0, duration, int(fs*duration)), 1, duration, f).astype(np.float32) # sweep
stream = p.open(format=pyaudio.paFloat32, channels=1, rate=fs, output=True) # for paFloat32 sample values must be in range [-1.0, 1.0]
stream.write((volume*samples).tobytes())
stream.write((volume*samples2).tobytes())
stream.write((volume*samples3).tobytes())
stream.write((volume*samples4).tobytes())
write("out.wav", fs, volume*samples4)
stream.stop_stream()
stream.close()
p.terminate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment