Advertisement
Lucun_Ji

player.py

Jul 3rd, 2022 (edited)
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. import asyncio
  2. import os
  3. import sys
  4. from asyncio.protocols import SubprocessProtocol
  5. from asyncio.subprocess import PIPE, DEVNULL
  6.  
  7. import loguru
  8.  
  9.  
  10. class SubprocLoggerProtocol(SubprocessProtocol):
  11.     def __init__(self, label: str):
  12.         self.label = label
  13.  
  14.     def pipe_data_received(self, fd: int, data: bytes) -> None:
  15.         for line in data.decode().splitlines():
  16.             loguru.logger.debug(f'{self.label}(fd={fd}): {line}')
  17.  
  18.  
  19. async def main():
  20.     media_r, media_w = os.pipe()
  21.     os.set_inheritable(media_r, True)
  22.     os.set_inheritable(media_w, True)
  23.     cdk_transport, _ = await asyncio.get_event_loop().subprocess_exec(
  24.         lambda: SubprocLoggerProtocol('CDK'),
  25.         'ffplay', '-i', f'pipe:{media_r}',  # use ffplay for testing
  26.         # './voicevoice', '-t', os.getenv('TOKEN'), '-c', os.getenv('CHANNEL'), '-i', f'pipe:{media_r}',
  27.         close_fds=False, stdout=DEVNULL, stderr=PIPE, stdin=PIPE
  28.     )
  29.  
  30.     # encoding, bitrate, sample rate, channels
  31.     common_output_params = ('-c:a', 'pcm_s16le', '-b:a', '1411200', '-ar', '44.1k', '-ac', '2')
  32.  
  33.     warmup_transport, _ = await asyncio.get_event_loop().subprocess_exec(  # warmup with empty music with header
  34.         lambda: SubprocLoggerProtocol('WARMUP'),
  35.         'ffmpeg',
  36.         '-f', 'lavfi', '-t', '0.0001', '-i', 'anullsrc',
  37.         '-f', 'wav', *common_output_params, f'pipe:{media_w}',
  38.         close_fds=False, stdout=DEVNULL, stderr=PIPE, stdin=DEVNULL
  39.     )
  40.     while warmup_transport.get_returncode() is None:
  41.         await asyncio.sleep(0)
  42.  
  43.     sender_transport, _ = await asyncio.get_event_loop().subprocess_exec(  # output raw music with no header
  44.         lambda: SubprocLoggerProtocol('SENDER'),
  45.         'ffmpeg', '-progress', f'pipe:{sys.stdout.fileno()}',
  46.         '-re', '-i', 'youkari.mp3',
  47.         '-f', 's16le', *common_output_params, f'pipe:{media_w}',
  48.         close_fds=False, stdout=PIPE, stderr=PIPE, stdin=DEVNULL
  49.     )
  50.     while sender_transport.get_returncode() is None and cdk_transport.get_returncode() is None:
  51.         await asyncio.sleep(0)
  52.     sender_transport.close()
  53.  
  54.     cdk_transport.close()
  55.     os.close(media_r)
  56.     os.close(media_w)
  57.  
  58.  
  59. if __name__ == '__main__':
  60.     asyncio.new_event_loop().run_until_complete(main())
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement