Created
November 29, 2023 15:04
-
-
Save thevickypedia/550a782c48bba7429dc9af4d70445295 to your computer and use it in GitHub Desktop.
Record and play audio using pyaudio module
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 logging | |
import math | |
import pyaudio | |
_logger = logging.getLogger(__name__) | |
_logger.addHandler(logging.StreamHandler()) | |
_logger.setLevel(logging.DEBUG) | |
class Audio: | |
def __init__(self, logger: logging.Logger = _logger, sample_rate: int = 22050): | |
self.chunk = 1024 | |
self.rate = sample_rate | |
self.logger = logger | |
__audio_engine = pyaudio.PyAudio() | |
self.stream = __audio_engine.open( | |
format=pyaudio.paInt16, | |
channels=1, | |
rate=self.rate, | |
input=True, | |
output=True, | |
frames_per_buffer=self.chunk | |
) | |
def record(self, seconds): | |
self.logger.info("Recording") | |
for i in range(0, math.ceil(self.rate / self.chunk * seconds)): | |
yield self.stream.read(self.chunk) | |
self.logger.info("Stopped recording") | |
def play(self, data): | |
self.logger.info("Playing") | |
for i in range(0, len(data), self.chunk): | |
self.stream.write(data[i:i + self.chunk]) | |
self.logger.info("Stopped playing") | |
if __name__ == '__main__': | |
audio = Audio() | |
recorded = b''.join(list(audio.record(5))) | |
audio.play(recorded) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment