kind of working
This commit is contained in:
52
audio_handler.py
Normal file
52
audio_handler.py
Normal file
@@ -0,0 +1,52 @@
|
||||
import pyaudio
|
||||
import threading
|
||||
import time
|
||||
from config import SAMPLE_RATE, CHUNK_SIZE
|
||||
|
||||
|
||||
class AudioHandler:
|
||||
def __init__(self):
|
||||
self.audio = pyaudio.PyAudio()
|
||||
self.stream = None
|
||||
self.is_listening = False
|
||||
self.callback = None
|
||||
|
||||
def start_listening(self, callback):
|
||||
"""Начать прослушивание микрофона"""
|
||||
self.callback = callback
|
||||
self.is_listening = True
|
||||
|
||||
# Открываем поток для записи аудио
|
||||
self.stream = self.audio.open(
|
||||
format=pyaudio.paInt16,
|
||||
channels=1,
|
||||
rate=SAMPLE_RATE,
|
||||
input=True,
|
||||
frames_per_buffer=CHUNK_SIZE
|
||||
)
|
||||
|
||||
# Запускаем поток для обработки аудио
|
||||
self.thread = threading.Thread(target=self._listen)
|
||||
self.thread.start()
|
||||
|
||||
def stop_listening(self):
|
||||
"""Остановить прослушивание микрофона"""
|
||||
self.is_listening = False
|
||||
if self.stream:
|
||||
self.stream.stop_stream()
|
||||
self.stream.close()
|
||||
|
||||
def _listen(self):
|
||||
"""Поток для прослушивания аудио"""
|
||||
while self.is_listening:
|
||||
try:
|
||||
data = self.stream.read(CHUNK_SIZE, exception_on_overflow=False)
|
||||
if self.callback:
|
||||
self.callback(data)
|
||||
except Exception as e:
|
||||
print(f"Ошибка при чтении аудио: {e}")
|
||||
break
|
||||
|
||||
def __del__(self):
|
||||
if self.audio:
|
||||
self.audio.terminate()
|
||||
Reference in New Issue
Block a user