#!/usr/bin/env python3
"""
合成所有双语音频（432句）- 中文 + 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):
    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静音文件")

print(f"合成 {432} 句双语音频...")

for i in range(432):
    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

    if i % 50 == 0:
        print(f"  处理句 {i}/432")

    # 转换TTS格式
    tts_converted = os.path.join(temp_dir, f"tts_converted_{idx}.wav")
    convert_cmd = [
        'ffmpeg', '-y',
        '-i', tts_file,
        '-c:a', 'pcm_s16le',
        '-ar', '44100',
        '-ac', '1',
        tts_converted
    ]
    subprocess.run(convert_cmd, capture_output=True)

    # 创建拼接列表
    list_file = os.path.join(temp_dir, f"concat_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
    ]
    subprocess.run(concat_cmd, capture_output=True)

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

print(f"完成！双语音频保存在: {output_dir}")
