#!/usr/bin/env python3
"""
拼接中文音频和英文TTS，生成双语音频（前10句）- 添加400ms间隔
策略：中文音频 + 400ms静音 + 英文TTS
"""
import os
import subprocess

# 输入目录
cn_dir = "shitu_audio_segments"
tts_dir = "shitu_tts"

# 输出目录
output_dir = "shitu_bilingual"
temp_dir = "shitu_temp_audio"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
if not os.path.exists(temp_dir):
    os.makedirs(temp_dir)

# 静音文件（400ms）
silence_file = os.path.join(temp_dir, "silence_400ms.wav")
if not os.path.exists(silence_file):
    # 生成400ms静音
    silence_cmd = [
        'ffmpeg', '-y',
        '-f', 'lavfi',
        '-i', 'anullsrc=r=44100:cl=mono',
        '-t', '0.4',
        '-c:a', 'pcm_s16le',
        '-ar', '44100',
        '-ac', '1',
        silence_file
    ]
    subprocess.run(silence_cmd, capture_output=True)
    print("生成400ms静音文件")

# 处理前10句
print("生成双语音频（前10句）- 添加400ms间隔")
print("=" * 50)

for i in range(10):
    idx = f"{i:03d}"
    cn_file = os.path.join(cn_dir, f"audio_line_{idx}.wav")
    tts_file = os.path.join(tts_dir, f"tts_line_{idx}.wav")
    output_file = os.path.join(output_dir, f"bilingual_line_{idx}.wav")

    # 检查文件是否存在
    if not os.path.exists(cn_file):
        print(f"  句{i}: 中文音频不存在")
        continue
    if not os.path.exists(tts_file):
        print(f"  句{i}: TTS音频不存在")
        continue

    print(f"  句{i}: 处理中...")

    # 第一步：将TTS转换为与中文音频相同的格式
    tts_converted = os.path.join(temp_dir, f"tts_{idx}_converted.wav")
    convert_cmd = [
        'ffmpeg', '-y',
        '-i', tts_file,
        '-c:a', 'pcm_s16le',
        '-ar', '44100',
        '-ac', '1',
        tts_converted
    ]
    result = subprocess.run(convert_cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')
    if result.returncode != 0:
        print(f"    TTS转换失败")
        continue

    # 第二步：拼接：中文 + 400ms静音 + TTS
    list_file = os.path.join(temp_dir, f"list_{idx}.txt")
    with open(list_file, 'w', encoding='utf-8') as f:
        f.write(f"file '{os.path.abspath(cn_file).replace('\\', '/')}'\n")
        f.write(f"file '{os.path.abspath(silence_file).replace('\\', '/')}'\n")
        f.write(f"file '{os.path.abspath(tts_converted).replace('\\', '/')}'\n")

    concat_cmd = [
        'ffmpeg', '-y',
        '-f', 'concat',
        '-safe', '0',
        '-i', list_file,
        '-c:a', 'pcm_s16le',
        '-ar', '44100',
        '-ac', '1',
        output_file
    ]
    result = subprocess.run(concat_cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')

    if result.returncode == 0:
        # 获取输出文件时长
        probe_cmd = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
                     '-of', 'default=noprint_wrappers=1:nokey=1', output_file]
        probe_result = subprocess.run(probe_cmd, capture_output=True, text=True)
        duration = float(probe_result.stdout.strip()) if probe_result.returncode == 0 else 0

        # 获取各部分时长
        probe_cn = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
                                   '-of', 'default=noprint_wrappers=1:nokey=1', cn_file],
                                  capture_output=True, text=True)
        probe_tts = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
                                    '-of', 'default=noprint_wrappers=1:nokey=1', tts_converted],
                                   capture_output=True, text=True)
        cn_dur = float(probe_cn.stdout.strip()) if probe_cn.returncode == 0 else 0
        tts_dur = float(probe_tts.stdout.strip()) if probe_tts.returncode == 0 else 0

        print(f"    完成: {duration:.2f}s (中文{cn_dur:.2f}s + 0.4s间隔 + TTS{tts_dur:.2f}s)")
    else:
        print(f"    错误")

    # 清理临时文件
    if os.path.exists(list_file):
        os.remove(list_file)

print("\n" + "=" * 50)
print(f"完成！双语音频保存在: {output_dir}")

# 验证结果
print("\n验证结果:")
print("-" * 50)
for i in range(10):
    idx = f"{i:03d}"
    output_file = os.path.join(output_dir, f"bilingual_line_{idx}.wav")
    if os.path.exists(output_file):
        cmd = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
               '-of', 'default=noprint_wrappers=1:nokey=1', output_file]
        result = subprocess.run(cmd, capture_output=True, text=True)
        duration = float(result.stdout.strip()) if result.returncode == 0 else 0
        print(f"  句{i}: {duration:.2f}s")
