import subprocess
import time
from datetime import datetime
import os

# RTSP 流地址
rtsp_url = "rtsp://10.68.66.174/audio"

# 录制时长（分钟）
duration_minutes = 60
output_filename = f"rtsp_recording_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"

print(f"开始录制 RTSP 音频流...")
print(f"RTSP 地址: {rtsp_url}")
print(f"录制时长: {duration_minutes} 分钟")
print(f"保存路径: {output_filename}")
print(f"按 Ctrl+C 停止录制")
print("-" * 50)

# 转换为秒
duration_seconds = duration_minutes * 60

try:
    # 使用 ffmpeg 录制 RTSP 流
    # -rtsp_transport tcp 使用 TCP 协议，更稳定
    # -t 指定录制时长
    # -acodec pcm_s16le 输出 PCM WAV 格式
    cmd = [
        'ffmpeg',
        '-rtsp_transport', 'tcp',
        '-i', rtsp_url,
        '-t', str(duration_seconds),
        '-acodec', 'pcm_s16le',
        '-ar', '16000',  # 采样率
        '-ac', '1',      # 单声道
        '-y',            # 覆盖已存在的文件
        output_filename
    ]
    
    print(f"执行命令: {' '.join(cmd)}")
    print("开始录制...")
    
    # 执行 ffmpeg 命令
    process = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True
    )
    
    # 用于跟踪进度的变量
    start_time = time.time()
    last_size = 0
    
    # 实时输出 ffmpeg 的日志
    for line in iter(process.stdout.readline, ''):
        if line:
            # 检查文件大小变化
            if os.path.exists(output_filename):
                current_size = os.path.getsize(output_filename)
                if current_size != last_size:
                    elapsed = time.time() - start_time
                    size_mb = current_size / (1024 * 1024)
                    progress = (elapsed / duration_seconds) * 100 if duration_seconds > 0 else 0
                    print(f"进度: {int(elapsed)}秒 / {duration_seconds}秒 ({progress:.1f}%), 大小: {size_mb:.2f}MB", end='\r')
                    last_size = current_size
    
    process.wait()
    
    # 录制完成
    elapsed = time.time() - start_time
    if os.path.exists(output_filename):
        size_mb = os.path.getsize(output_filename) / (1024 * 1024)
        print(f"\n\n录制完成!")
        print(f"总时长: {int(elapsed)}秒 ({elapsed/60:.1f}分钟)")
        print(f"文件大小: {size_mb:.2f}MB")
        print(f"保存路径: {os.path.abspath(output_filename)}")
    else:
        print("\n录制失败，文件未生成")
    
except KeyboardInterrupt:
    print(f"\n\n录制已手动停止")
    if os.path.exists(output_filename):
        size_mb = os.path.getsize(output_filename) / (1024 * 1024)
        elapsed = time.time() - start_time
        print(f"已录制: {int(elapsed)}秒")
        print(f"文件大小: {size_mb:.2f}MB")
        print(f"保存路径: {os.path.abspath(output_filename)}")
except Exception as e:
    print(f"\n错误: {e}")
