📜  Python 录制直播流 (TS FILES) - Python (1)

📅  最后修改于: 2023-12-03 15:19:09.640000             🧑  作者: Mango

Python 录制直播流 (TS FILES) - Python

在这篇文章中,我们将介绍如何使用 Python 语言来录制直播流并保存为 .ts 文件。

HTTP/HTTPS 直播流

如果想要录制 HTTP/HTTPS 直播流,可以使用 Python 的 requests 模块和 ffmpeg 工具,如下所示:

import subprocess
import requests

url = 'http://example.com/live/stream.m3u8'
output_file = 'output.ts'

# Download m3u8 file
response = requests.get(url)
m3u8_content = response.text

# Parse m3u8 file and construct ffmpeg command
lines = m3u8_content.split('\n')
video_line = [line for line in lines if '.ts' in line][0]
video_url = url.rsplit('/', 1)[0] + '/' + video_line
ffmpeg_cmd = ['ffmpeg', '-i', video_url, '-c', 'copy', output_file]

# Start recording
subprocess.Popen(ffmpeg_cmd)

上述代码将下载 m3u8 文件,解析出其中的视频流 URL,然后使用 ffmpeg 工具来录制视频流并将其保存为 .ts 文件。

RTMP 直播流

如果想要录制 RTMP 直播流,可以使用 Python 的 subprocess 模块和 ffmpeg 工具,如下所示:

import subprocess

url = 'rtmp://example.com/live/stream'
output_file = 'output.ts'

ffmpeg_cmd = ['ffmpeg', '-i', url, '-c', 'copy', output_file]

# Start recording
subprocess.Popen(ffmpeg_cmd)

上述代码将使用 ffmpeg 工具来录制 RTMP 直播流并将其保存为 .ts 文件。

结论

在本文中,我们介绍了如何使用 Python 语言来录制直播流并保存为 .ts 文件。不论你需要处理 HTTP/HTTPS 直播流或 RTMP 直播流,Python 都是一个非常有用的工具。