const OPENAI_PCM_SR = 24000; // OpenAI /audio/speech pcm output is 24kHz s16le mono
export async function openaiSynthesizePcm(cfg, text, opts) {
    const clean = text.trim();
    if (!clean)
        throw new Error('没有要合成的文字');
    if (!cfg.baseUrl || !cfg.model)
        throw new Error('OpenAI 兼容引擎配置不完整（需要 baseUrl / model）。');
    const url = `${cfg.baseUrl.replace(/\/$/, '')}/audio/speech`;
    const body = {
        model: cfg.model,
        input: clean,
        voice: opts.speaker,
        response_format: 'pcm',
    };
    if (opts.rate && opts.rate !== 1)
        body.speed = Math.max(0.25, Math.min(4, opts.rate));
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 60000);
    try {
        const res = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                ...(cfg.apiKey ? { Authorization: `Bearer ${cfg.apiKey}` } : {}),
            },
            body: JSON.stringify(body),
            signal: controller.signal,
        });
        if (!res.ok) {
            const detail = await res.text().catch(() => '');
            throw new Error(`TTS HTTP ${res.status}: ${detail.slice(0, 200)}`);
        }
        const data = Buffer.from(await res.arrayBuffer());
        if (!data.length)
            throw new Error('TTS 返回空音频');
        return { data, sampleRate: OPENAI_PCM_SR, channels: 1 };
    }
    catch (e) {
        if (e?.name === 'AbortError')
            throw new Error('TTS 合成超时');
        throw e;
    }
    finally {
        clearTimeout(timer);
    }
}
//# sourceMappingURL=openai.js.map