|
| 1 | +"""backend_dummy.py |
| 2 | +
|
| 3 | +This file contains the dummy backend for bluebox. |
| 4 | +This is used for testing and instead of generating |
| 5 | +sound, it can print the data to the console, or return |
| 6 | +it as a list. |
| 7 | +""" |
| 8 | + |
| 9 | +import typing as t |
| 10 | +import logging |
| 11 | +from .base import BlueboxBackend |
| 12 | + |
| 13 | + |
| 14 | +class DummyBackend(BlueboxBackend): |
| 15 | + """DummyBackend class for the dummy backend.""" |
| 16 | + |
| 17 | + _data: t.List[float] |
| 18 | + |
| 19 | + def __init__( |
| 20 | + self, |
| 21 | + sample_rate: float = 44100.0, |
| 22 | + channels: int = 1, |
| 23 | + amplitude: float = 1.0, |
| 24 | + logger: t.Optional[logging.Logger] = None, |
| 25 | + mode: str = 'print') -> None: |
| 26 | + """Initialize the dummy backend.""" |
| 27 | + super().__init__(sample_rate, channels, amplitude, logger) |
| 28 | + self._mode = mode |
| 29 | + self._data = [] |
| 30 | + |
| 31 | + def _to_bytes(self, data: t.Iterator[float]) -> t.List[float]: |
| 32 | + """Wrap the data in a buffer.""" |
| 33 | + _data = [] |
| 34 | + while True: |
| 35 | + try: |
| 36 | + d = next(data) |
| 37 | + _data.append(d) |
| 38 | + except StopIteration: |
| 39 | + break |
| 40 | + |
| 41 | + return _data |
| 42 | + |
| 43 | + def play(self, data: t.Iterator[float], close=True) -> None: |
| 44 | + """Play the given data.""" |
| 45 | + d = self._to_bytes(data) |
| 46 | + if self._mode == 'print': |
| 47 | + print(d) |
| 48 | + elif self._mode == 'list': |
| 49 | + self._data += d |
| 50 | + else: |
| 51 | + raise ValueError(f'Invalid mode: {self._mode}') |
| 52 | + |
| 53 | + def play_all(self, queue: t.Iterator[t.Iterator[float]]) -> None: |
| 54 | + """Play the given data and then stop.""" |
| 55 | + for data in queue: |
| 56 | + self.play(data, close=False) |
| 57 | + |
| 58 | + def stop(self) -> None: |
| 59 | + """Stop playing the data.""" |
| 60 | + pass |
| 61 | + |
| 62 | + def close(self) -> None: |
| 63 | + """Close the backend.""" |
| 64 | + pass |
| 65 | + |
| 66 | + def __del__(self) -> None: |
| 67 | + """Delete the backend.""" |
| 68 | + self.close() |
| 69 | + |
| 70 | + def get_data(self) -> t.List[float]: |
| 71 | + """Get the data.""" |
| 72 | + return self._data |
| 73 | + |
| 74 | + def clear_data(self) -> None: |
| 75 | + """Clear the data.""" |
| 76 | + self._data = [] |
0 commit comments