download_video.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import html
  2. import subprocess
  3. import time
  4. import requests
  5. class DownLoad:
  6. @classmethod
  7. def download_video(cls, video_url, video_path_url):
  8. video = video_path_url + 'video.mp4'
  9. url_type = html.unescape(video_url).split('?')[0]
  10. if ".m3u8" in url_type:
  11. ffmpeg_cmd_oss = [
  12. "ffmpeg",
  13. "-y", # 覆盖输出文件
  14. "-i", video_url, # 输入文件
  15. "-c", "copy", # 复制视频流
  16. "-bsf:a", "aac_adtstoasc", # 转换 AAC 音频格式
  17. video # 输出文件
  18. ]
  19. # 使用 subprocess 运行命令
  20. subprocess.run(ffmpeg_cmd_oss, capture_output=True, text=True)
  21. return video
  22. else:
  23. try:
  24. for i in range(3):
  25. payload = {}
  26. headers = {}
  27. response = requests.request("GET", video_url, headers=headers, data=payload, timeout=240)
  28. if response.status_code == 200:
  29. # 以二进制写入模式打开文件
  30. with open(f"{video}", "wb") as file:
  31. # 将响应内容写入文件
  32. file.write(response.content)
  33. time.sleep(5)
  34. return video
  35. return None
  36. except Exception:
  37. return None