Created
April 1, 2020 22:25
-
-
Save hdf/9b244f74b211b51c77d81cc77bdbcee1 to your computer and use it in GitHub Desktop.
Waveform generation example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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