Skip to content

Instantly share code, notes, and snippets.

@aliwo
Created December 23, 2020 08:04
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 aliwo/318b4af2ad697820dc6ccc9d2140b229 to your computer and use it in GitHub Desktop.
Save aliwo/318b4af2ad697820dc6ccc9d2140b229 to your computer and use it in GitHub Desktop.
keyboardinterrupt 로 중간에 멈추는 녹음
import pyaudio
import wave
chunk = 1024 # Record in chunks of 1024 samples
sample_format = pyaudio.paInt16 # 16 bits per sample
channels = 1
fs = 44100 # Record at 44100 samples per second
seconds = 3
filename = "output.wav"
p = pyaudio.PyAudio() # Create an interface to PortAudio
print('Recording')
stream = p.open(format=sample_format,
channels=channels,
rate=fs,
frames_per_buffer=chunk,
input=True)
frames = [] # Initialize array to store frames
# Store data in chunks for 3 seconds
while True:
try:
data = stream.read(chunk)
frames.append(data)
except KeyboardInterrupt:
print('녹음 종료!')
break
# Stop and close the stream
stream.stop_stream()
stream.close()
# Terminate the PortAudio interface
p.terminate()
print('Finished recording')
# Save the recorded data as a WAV file
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(sample_format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment