recorder.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import asyncio
  2. from datetime import datetime
  3. from string import Template
  4. from bilibili_api import live
  5. import ffmpy3
  6. class Recorder:
  7. def __init__(self,room_display_id):
  8. self.ROOM_DISPLAY_ID=room_display_id
  9. async def __getInfoAndUrl(self,l):
  10. return await l.get_room_info(), await l.get_room_play_url(live.ScreenResolution.FOUR_K)
  11. def start(self, outputNameTemplate: str = '【${qn_desc}】${name} - ${datetime}', log: bool = True):
  12. OUTPUT_NAME_TEMPLATE=Template(outputNameTemplate)
  13. l = live.LiveRoom(room_display_id=self.ROOM_DISPLAY_ID)
  14. info, play_url = asyncio.get_event_loop().run_until_complete(self.__getInfoAndUrl(l))
  15. anchor_info=info["anchor_info"]["base_info"]
  16. current_qn = play_url["current_qn"]
  17. quality_descriptions = play_url["quality_description"]
  18. durl = play_url["durl"]
  19. current_qn_desc = "未知清晰度"
  20. for quality_description in quality_descriptions:
  21. if(current_qn == quality_description["qn"]):
  22. current_qn_desc = quality_description["desc"]
  23. url = durl[len(durl)-1]["url"]
  24. outputName = OUTPUT_NAME_TEMPLATE.safe_substitute({
  25. 'name': anchor_info["uname"],
  26. 'qn_desc': current_qn_desc,
  27. 'datetime': datetime.now().isoformat()
  28. })
  29. f_handler=open("./logs/"+outputName+'.log', 'w') if log else asyncio.subprocess.PIPE
  30. self.ff = ffmpy3.FFmpeg(
  31. inputs={url:" -v debug"},
  32. outputs={"./videos/"+outputName+".flv":"-c copy -y"}
  33. )
  34. self.process = self.ff.run_async(stdout=f_handler, stderr=f_handler)
  35. print(self.ff.cmd)
  36. asyncio.get_event_loop().run_until_complete(self.process)
  37. asyncio.get_event_loop().run_until_complete(self.ff.wait())
  38. print(self.process)
  39. def stop(self):
  40. self.process.terminate()