| 1 |
"""Microphone input.""" |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import contextlib |
| 5 |
import logging |
| 6 |
import time |
| 7 |
from asyncio.subprocess import Process |
| 8 |
from typing import List, Optional |
| 9 |
|
| 10 |
from .audio import AudioChunk |
| 11 |
from .client import AsyncClient |
| 12 |
from .event import Event |
| 13 |
|
| 14 |
_LOGGER = logging.getLogger(__name__) |
| 15 |
|
| 16 |
DOMAIN = "mic" |
| 17 |
|
| 18 |
|
| 19 |
class MicProcessAsyncClient(AsyncClient, contextlib.AbstractAsyncContextManager): |
| 20 |
"""Context manager for getting microphone audio from an external program.""" |
| 21 |
|
| 22 |
def __init__( |
| 23 |
self, |
| 24 |
rate: int, |
| 25 |
width: int, |
| 26 |
channels: int, |
| 27 |
samples_per_chunk: int, |
| 28 |
program: str, |
| 29 |
program_args: List[str], |
| 30 |
) -> None: |
| 31 |
super().__init__() |
| 32 |
|
| 33 |
self.rate = rate |
| 34 |
self.width = width |
| 35 |
self.channels = channels |
| 36 |
self.samples_per_chunk = samples_per_chunk |
| 37 |
self.bytes_per_chunk = samples_per_chunk * width * channels |
| 38 |
self.program = program |
| 39 |
self.program_args = program_args |
| 40 |
|
| 41 |
self._proc: Optional[Process] = None |
| 42 |
|
| 43 |
async def connect(self) -> None: |
| 44 |
self._proc = await asyncio.create_subprocess_exec( |
| 45 |
self.program, *self.program_args, stdout=asyncio.subprocess.PIPE |
| 46 |
) |
| 47 |
|
| 48 |
async def disconnect(self) -> None: |
| 49 |
assert self._proc is not None |
| 50 |
|
| 51 |
try: |
| 52 |
if self._proc.returncode is None: |
| 53 |
# Terminate process gracefully |
| 54 |
self._proc.terminate() |
| 55 |
await self._proc.wait() |
| 56 |
except ProcessLookupError: |
| 57 |
# Expected when process has already exited |
| 58 |
pass |
| 59 |
except Exception: |
| 60 |
_LOGGER.exception("Unexpected error stopping process: %s", self.program) |
| 61 |
finally: |
| 62 |
self._proc = None |
| 63 |
|
| 64 |
async def __aenter__(self) -> "MicProcessAsyncClient": |
| 65 |
await self.connect() |
| 66 |
return self |
| 67 |
|
| 68 |
async def __aexit__(self, exc_type, exc, tb): |
| 69 |
await self.disconnect() |
| 70 |
|
| 71 |
async def read_event(self) -> Optional[Event]: |
| 72 |
assert self._proc is not None |
| 73 |
assert self._proc.stdout is not None |
| 74 |
|
| 75 |
try: |
| 76 |
audio_bytes = await self._proc.stdout.readexactly(self.bytes_per_chunk) |
| 77 |
return AudioChunk( |
| 78 |
rate=self.rate, |
| 79 |
width=self.width, |
| 80 |
channels=self.channels, |
| 81 |
audio=audio_bytes, |
| 82 |
timestamp=time.monotonic_ns(), |
| 83 |
).event() |
| 84 |
except asyncio.IncompleteReadError: |
| 85 |
return None |
| 86 |
|
| 87 |
async def write_event(self, event: Event) -> None: |
| 88 |
"""Client is read-only.""" |