python之使用ffmpeg下载直播推流视频rtmp、m3u8协议实时获取时间进度

一、ffmpeg下载

录制函数

python 复制代码
    def download_video_by_live_url():
		playUrl = "rtmp://....."    #推流url:rtmp、m3u8等
        print(f"已开始录制: playUrl:{playUrl}")

        now_time = datetime.now().strftime('%Y_%m_%d__%H_%M_%S')
        output_file =  now_time + ".mp4"
        output_file = re.sub(r'[\\/:*?"<>|]', '', output_file)
        ffmpeg_command = [
            "ffmpeg",
            "-i", playUrl,
            "-c", "copy",
            "-f", "mp4",
            output_file
        ]

        process = subprocess.Popen(
            ffmpeg_command,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,  # decode bytes to str
            encoding="utf-8",
            bufsize=1
        )

        time_pattern = re.compile(r'time=(\d+:\d+:\d+\.\d+)')
        start_time = time.time()
        try:
            for line in process.stderr:
                line = line.strip()
                if 'time=' in line:
                    match = time_pattern.search(line)
                    if match and time.time() - start_time > 10:
                        start_time = time.time()
                        current_time = match.group(1)
                        print(f" Progress: {current_time}", flush=True)
                if 'No such stream' in line:
                    print(f"直播结束,结束录制!")
                    break


        except KeyboardInterrupt:
            print(f"检测到手动中断,正在优雅停止 ffmpeg...")
            process.stdin.write('q'.encode("GBK"))
            process.communicate()
            process.kill()
        except Exception as e:
            print(f"[{current_name}][{nickname}]录制出错: {e}")

        process.wait()
相关推荐
Android系统攻城狮38 分钟前
Android16音频之获取录制状态AudioRecord.getRecordingState:用法实例(一百七十六)
音视频·android16·音频进阶
Learn-Python1 小时前
MongoDB-only方法
python·sql
小途软件2 小时前
用于机器人电池电量预测的Sarsa强化学习混合集成方法
java·人工智能·pytorch·python·深度学习·语言模型
扫地的小何尚3 小时前
NVIDIA RTX PC开源AI工具升级:加速LLM和扩散模型的性能革命
人工智能·python·算法·开源·nvidia·1024程序员节
wanglei2007083 小时前
生产者消费者
开发语言·python
清水白石0083 小时前
《从零到进阶:Pydantic v1 与 v2 的核心差异与零成本校验实现原理》
数据库·python
昵称已被吞噬~‘(*@﹏@*)’~3 小时前
【RL+空战】学习记录03:基于JSBSim构造简易空空导弹模型,并结合python接口调用测试
开发语言·人工智能·python·学习·深度强化学习·jsbsim·空战
2501_941877984 小时前
从配置热更新到运行时自适应的互联网工程语法演进与多语言实践随笔分享
开发语言·前端·python
酩酊仙人4 小时前
fastmcp构建mcp server和client
python·ai·mcp
且去填词4 小时前
DeepSeek API 深度解析:从流式输出、Function Calling 到构建拥有“手脚”的 AI 应用
人工智能·python·语言模型·llm·agent·deepseek