Last active
August 18, 2019 06:44
-
-
Save pranav6670/54338fe7ee965bdb8be664cd73efd0ee to your computer and use it in GitHub Desktop.
Record audio using PyAudio in real-time
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
self.FORMAT = pyaudio.paInt16 | |
self.CHANNELS = 1 | |
self.RATE = 44100 | |
self.CHUNK = 1024 | |
self.WAVE_OUTPUT_FILENAME = "file.wav" | |
self.RECORD_SECONDS = 20 | |
def record(self): | |
self.audio = pyaudio.PyAudio() | |
# start Recording | |
self.stream = self.audio.open(format=self.FORMAT, channels=self.CHANNELS, | |
rate=self.RATE, input=True, frames_per_buffer=self.CHUNK) | |
print("recording...") | |
self.frames = [] | |
for i in range(0, int(self.RATE / self.CHUNK * self.RECORD_SECONDS)): | |
self.data = self.stream.read(self.CHUNK) | |
self.frames.append(self.data) | |
# stop Recording | |
self.stream.stop_stream() | |
self.stream.close() | |
self.audio.terminate() | |
self.waveFile = wave.open(self.WAVE_OUTPUT_FILENAME, 'wb') | |
self.waveFile.setnchannels(self.CHANNELS) | |
self.waveFile.setsampwidth(self.audio.get_sample_size(self.FORMAT)) | |
self.waveFile.setframerate(self.RATE) | |
self.waveFile.writeframes(b''.join(self.frames)) | |
self.waveFile.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment