import requests
import time
from datetime import datetime

url = "http://10.68.66.174/mix.wav"
duration_minutes = 60  # 录制时长（分钟）
output_file = f"recording_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"

duration_seconds = duration_minutes * 60
print(f"开始录制音频流...")
print(f"录制时长: {duration_minutes} 分钟")
print(f"保存路径: {output_file}")

start_time = time.time()
chunk_size = 8192
total_bytes = 0
last_print_time = 0

try:
    response = requests.get(url, stream=True, timeout=60)
    response.raise_for_status()
    
    with open(output_file, 'wb') as f:
        for chunk in response.iter_content(chunk_size=chunk_size):
            if chunk:
                f.write(chunk)
                total_bytes += len(chunk)
                
                elapsed = time.time() - start_time
                
                # 每10秒打印一次进度
                if int(elapsed) - last_print_time >= 10:
                    last_print_time = int(elapsed)
                    size_mb = total_bytes / (1024 * 1024)
                    remaining = int(duration_seconds - elapsed)
                    print(f"已录制: {int(elapsed)}秒 / {duration_seconds}秒 ({elapsed/duration_seconds*100:.1f}%), 大小: {size_mb:.2f}MB, 剩余: {remaining}秒")
                
                # 达到指定时长后自动停止
                if elapsed >= duration_seconds:
                    print(f"\n已达到指定录制时长 {duration_minutes} 分钟")
                    break
    
    elapsed = time.time() - start_time
    size_mb = total_bytes / (1024 * 1024)
    print(f"\n录制完成!")
    print(f"总时长: {int(elapsed)}秒 ({elapsed/60:.1f}分钟)")
    print(f"文件大小: {size_mb:.2f}MB")
    print(f"保存路径: {output_file}")
    
except KeyboardInterrupt:
    elapsed = time.time() - start_time
    size_mb = total_bytes / (1024 * 1024)
    print(f"\n录制已手动停止")
    print(f"总时长: {int(elapsed)}秒 ({elapsed/60:.1f}分钟)")
    print(f"文件大小: {size_mb:.2f}MB")
    print(f"保存路径: {output_file}")
except Exception as e:
    print(f"错误: {e}")
