|
| 1 | +"""backend_pyaudio.py |
| 2 | +
|
| 3 | +This file contains the PyAudio backend for bluebox. |
| 4 | +""" |
| 5 | + |
| 6 | +import typing as t |
| 7 | +import logging |
| 8 | +import struct |
| 9 | +import pyaudio # type: ignore |
| 10 | +from .base import BlueboxBackend |
| 11 | + |
| 12 | + |
| 13 | +class PyAudioBackend(BlueboxBackend): |
| 14 | + """PyAudioBackend class for the PyAudio backend.""" |
| 15 | + |
| 16 | + _stream: pyaudio.Stream |
| 17 | + _stream_open: bool = False |
| 18 | + _device: t.Union[int, None] |
| 19 | + |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + sample_rate: float = 44100.0, |
| 23 | + channels: int = 1, |
| 24 | + amplitude: float = 1.0, |
| 25 | + logger: t.Optional[logging.Logger] = None, |
| 26 | + device: t.Union[int, None] = None) -> None: |
| 27 | + """Initialize the PyAudio backend.""" |
| 28 | + super().__init__(sample_rate, channels, amplitude, logger) |
| 29 | + self._device = device |
| 30 | + |
| 31 | + def _get_stream( |
| 32 | + self, |
| 33 | + callback: t.Optional[t.Callable] = None) -> pyaudio.Stream: |
| 34 | + """Get the PyAudio stream.""" |
| 35 | + if not self._stream_open: |
| 36 | + self._stream = pyaudio.PyAudio().open( |
| 37 | + format=pyaudio.paFloat32, |
| 38 | + channels=self._ch, |
| 39 | + rate=int(self._sr), |
| 40 | + output=True, |
| 41 | + output_device_index=self._device, |
| 42 | + stream_callback=callback) |
| 43 | + self._stream_open = True |
| 44 | + return self._stream |
| 45 | + |
| 46 | + def _to_bytes(self, data: t.Iterator[float]) -> bytes: |
| 47 | + """Wrap the data in a buffer.""" |
| 48 | + _data = [] |
| 49 | + while True: |
| 50 | + try: |
| 51 | + d = next(data) |
| 52 | + _data.append(d) |
| 53 | + except StopIteration: |
| 54 | + break |
| 55 | + |
| 56 | + return struct.pack(f'{len(_data)}f', *_data) |
| 57 | + |
| 58 | + def play(self, data: t.Iterator[float], close=True) -> None: |
| 59 | + """Play the given data.""" |
| 60 | + d = self._to_bytes(data) |
| 61 | + self._get_stream().write(d) |
| 62 | + if close: |
| 63 | + self.close() |
| 64 | + |
| 65 | + def play_all(self, queue: t.Iterator[t.Iterator[float]]) -> None: |
| 66 | + """Play all the items until the end.""" |
| 67 | + while True: |
| 68 | + try: |
| 69 | + data = next(queue) |
| 70 | + self.play(data, False) |
| 71 | + except StopIteration: |
| 72 | + break |
| 73 | + self.close() |
| 74 | + |
| 75 | + def stop(self) -> None: |
| 76 | + """Stop playing the data.""" |
| 77 | + if self._stream_open: |
| 78 | + self._stream.stop_stream() |
| 79 | + |
| 80 | + def close(self) -> None: |
| 81 | + """Close the backend.""" |
| 82 | + if self._stream_open: |
| 83 | + self._stream.close() |
| 84 | + self._stream_open = False |
| 85 | + |
| 86 | + def __del__(self) -> None: |
| 87 | + """Close the backend.""" |
| 88 | + self.close() |
| 89 | + |
| 90 | + |
| 91 | +# class PyAudioBackendNonBlocking(PyAudioBackend): |
| 92 | +# """PyAudioBackendNonBlocking class for the PyAudio backend.""" |
| 93 | + |
| 94 | +# def _get_stream( |
| 95 | +# self, |
| 96 | +# callback: |
| 97 | +# t.Optional[t.Callable] = None) -> pyaudio.Stream: |
| 98 | +# """Get the PyAudio stream.""" |
| 99 | +# if not self._stream_open: |
| 100 | +# self._stream = pyaudio.PyAudio().open( |
| 101 | +# format=pyaudio.paFloat32, |
| 102 | +# channels=self._ch, |
| 103 | +# rate=int(self._sr), |
| 104 | +# output=True, |
| 105 | +# stream_callback=callback, |
| 106 | +# output_device_index=self._device) |
| 107 | +# self._stream_open = True |
| 108 | +# return self._stream |
| 109 | + |
| 110 | +# @property |
| 111 | +# def is_playing(self) -> bool: |
| 112 | +# """Return whether the stream is playing.""" |
| 113 | +# if not self._stream_open: |
| 114 | +# return False |
| 115 | +# return self._stream.is_active() |
| 116 | + |
| 117 | +# def play(self, data: t.Iterator[float], close=True) -> None: |
| 118 | +# """Play the given data.""" |
| 119 | +# total_frames = len(data) |
| 120 | +# frame_index = 0 |
| 121 | + |
| 122 | +# def stream_callback( |
| 123 | +# in_data: t.Optional[t.MutableSequence[bytes]], |
| 124 | +# frame_count: int, |
| 125 | +# time_info: t.Optional[dict], |
| 126 | +# status: t.Optional[int]) -> t.Tuple[ |
| 127 | +# t.Optional[t.MutableSequence[float]], |
| 128 | +# int]: |
| 129 | +# nonlocal frame_index |
| 130 | +# if frame_index >= total_frames: |
| 131 | +# return (None, pyaudio.paComplete) |
| 132 | +# frame_index += min(frame_count, total_frames - frame_index) |
| 133 | +# return ( |
| 134 | +# data[frame_index - frame_count:frame_index], |
| 135 | +# pyaudio.paContinue) |
| 136 | + |
| 137 | +# self._get_stream(stream_callback) |
| 138 | + |
| 139 | +# def play_all(self, queue: t.Iterator[t.MutableSequence[float]]) -> None: |
| 140 | +# """Not implemented. Probably should use asyncio.""" |
| 141 | +# raise NotImplementedError() |
0 commit comments