Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- import os
- import sys
- from asyncio.protocols import SubprocessProtocol
- from asyncio.subprocess import PIPE, DEVNULL
- import loguru
- class SubprocLoggerProtocol(SubprocessProtocol):
- def __init__(self, label: str):
- self.label = label
- def pipe_data_received(self, fd: int, data: bytes) -> None:
- for line in data.decode().splitlines():
- loguru.logger.debug(f'{self.label}(fd={fd}): {line}')
- async def main():
- media_r, media_w = os.pipe()
- os.set_inheritable(media_r, True)
- os.set_inheritable(media_w, True)
- cdk_transport, _ = await asyncio.get_event_loop().subprocess_exec(
- lambda: SubprocLoggerProtocol('CDK'),
- 'ffplay', '-i', f'pipe:{media_r}', # use ffplay for testing
- # './voicevoice', '-t', os.getenv('TOKEN'), '-c', os.getenv('CHANNEL'), '-i', f'pipe:{media_r}',
- close_fds=False, stdout=DEVNULL, stderr=PIPE, stdin=PIPE
- )
- # encoding, bitrate, sample rate, channels
- common_output_params = ('-c:a', 'pcm_s16le', '-b:a', '1411200', '-ar', '44.1k', '-ac', '2')
- warmup_transport, _ = await asyncio.get_event_loop().subprocess_exec( # warmup with empty music with header
- lambda: SubprocLoggerProtocol('WARMUP'),
- 'ffmpeg',
- '-f', 'lavfi', '-t', '0.0001', '-i', 'anullsrc',
- '-f', 'wav', *common_output_params, f'pipe:{media_w}',
- close_fds=False, stdout=DEVNULL, stderr=PIPE, stdin=DEVNULL
- )
- while warmup_transport.get_returncode() is None:
- await asyncio.sleep(0)
- sender_transport, _ = await asyncio.get_event_loop().subprocess_exec( # output raw music with no header
- lambda: SubprocLoggerProtocol('SENDER'),
- 'ffmpeg', '-progress', f'pipe:{sys.stdout.fileno()}',
- '-re', '-i', 'youkari.mp3',
- '-f', 's16le', *common_output_params, f'pipe:{media_w}',
- close_fds=False, stdout=PIPE, stderr=PIPE, stdin=DEVNULL
- )
- while sender_transport.get_returncode() is None and cdk_transport.get_returncode() is None:
- await asyncio.sleep(0)
- sender_transport.close()
- cdk_transport.close()
- os.close(media_r)
- os.close(media_w)
- if __name__ == '__main__':
- asyncio.new_event_loop().run_until_complete(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement