Created
March 24, 2020 12:28
-
-
Save cengiz-io/9c9932d402b2e3e220b9b4f7c7ed68ce to your computer and use it in GitHub Desktop.
This file contains 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 wave | |
import sys | |
"""" ------------------------------------------------------------ """ | |
""" ------------------------- RECORD ---------------------------- """ | |
""" ------------------------------------------------------------- """ | |
CHUNK = 1024 | |
FORMAT = pyaudio.paInt16 | |
CHANNELS = 2 | |
RATE = 44100 | |
RECORD_SECONDS = 5 | |
WAVE_OUTPUT_FILENAME = "output.wav" | |
p = pyaudio.PyAudio() | |
stream = p.open(format=FORMAT, | |
channels=CHANNELS, | |
rate=RATE, | |
input=True, | |
frames_per_buffer=CHUNK) | |
print("* recording") | |
frames = [] | |
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): | |
data = stream.read(CHUNK) | |
frames.append(data) | |
print("* done recording") | |
stream.stop_stream() | |
stream.close() | |
p.terminate() | |
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') | |
wf.setnchannels(CHANNELS) | |
wf.setsampwidth(p.get_sample_size(FORMAT)) | |
wf.setframerate(RATE) | |
wf.writeframes(b''.join(frames)) | |
wf.close() | |
""" ------------------------------------------------------------- """ | |
""" -------------------------- PLAY ----------------------------- """ | |
""" ------------------------------------------------------------- """ | |
CHUNK = 1024 | |
wf = wave.open("output.wav", 'rb') | |
print("* starting pyaudio") | |
p = pyaudio.PyAudio() | |
print("* opening stream") | |
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), | |
channels=wf.getnchannels(), | |
rate=wf.getframerate(), | |
output=True) | |
print("* reading frames") | |
data = wf.readframes(CHUNK) | |
print("* looping thru stream") | |
while data != b'': | |
stream.write(data) | |
data = wf.readframes(CHUNK) | |
print("* stopping stream") | |
stream.stop_stream() | |
print("* closing stream") | |
stream.close() | |
print("* terminating pyaudio") | |
p.terminate() | |
print("* exiting") | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment