Skip to content

Instantly share code, notes, and snippets.

@badjano
Last active January 7, 2019 08:11
Show Gist options
  • Save badjano/c727b20429295e2695afdbc601f2334b to your computer and use it in GitHub Desktop.
Save badjano/c727b20429295e2695afdbc601f2334b to your computer and use it in GitHub Desktop.
Generating, playing and saving audio
import wave
import numpy as np
import pyaudio
p = pyaudio.PyAudio()
volume = 0.5 # range [0.0, 1.0]
fs = 44100 # sampling rate, Hz, must be integer
duration = 2.0 # in seconds, may be float
f = 440.0 # sine frequency, Hz, may be float
channels = 1
# open stream (2)
stream = p.open(format=pyaudio.paInt32,
channels=channels,
rate=fs,
output=True)
def get_value(i):
return int(volume * np.sin(f * np.pi * float(i) / float(fs)) * 127)
samples = volume * np.array([get_value(a) for a in range(0, int(fs*duration))]).astype(np.int32)
for i in range(0, int(duration)):
stream.write(samples[i*fs:(i+1)*fs], fs)
wf = wave.open("test.wav", 'wb')
wf.setnchannels(channels)
wf.setsampwidth(4)
wf.setframerate(fs)
wf.setnframes(int(fs * duration))
wf.writeframes(samples)
wf.close()
# stop stream (4)
stream.stop_stream()
stream.close()
# close PyAudio (5)
p.terminate()
@rudrathegreat
Copy link

Just wondering, why are you using wave instead of scipy.io.wavfile.write?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment