2026-06-22 14:10:10 +08:00
|
|
|
|
// 语音转文字:使用 OpenAI Whisper API 或其他兼容服务
|
2026-06-22 14:59:24 +08:00
|
|
|
|
const WHISPER_API_KEY = process.env.WHISPER_API_KEY || process.env.DEEPSEEK_API_KEY || "";
|
|
|
|
|
|
const WHISPER_API_BASE = process.env.WHISPER_API_BASE || process.env.DEEPSEEK_BASE_URL || "https://api.openai.com/v1";
|
2026-06-22 14:10:10 +08:00
|
|
|
|
const WHISPER_MODEL = process.env.WHISPER_MODEL || "whisper-1";
|
|
|
|
|
|
|
|
|
|
|
|
export async function transcribeAudio(audioBuffer: ArrayBuffer, filename: string): Promise<string> {
|
|
|
|
|
|
if (!WHISPER_API_KEY) {
|
|
|
|
|
|
throw new Error("未配置语音转文字 API(设置 WHISPER_API_KEY 或 DEEPSEEK_API_KEY)");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const formData = new FormData();
|
|
|
|
|
|
const blob = new Blob([audioBuffer], { type: "audio/ogg" });
|
|
|
|
|
|
formData.append("file", blob, filename);
|
|
|
|
|
|
formData.append("model", WHISPER_MODEL);
|
|
|
|
|
|
formData.append("language", "zh");
|
|
|
|
|
|
|
|
|
|
|
|
const url = `${WHISPER_API_BASE}/audio/transcriptions`;
|
|
|
|
|
|
const res = await fetch(url, {
|
|
|
|
|
|
method: "POST",
|
|
|
|
|
|
headers: {
|
|
|
|
|
|
"Authorization": `Bearer ${WHISPER_API_KEY}`,
|
|
|
|
|
|
},
|
|
|
|
|
|
body: formData,
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
if (!res.ok) {
|
|
|
|
|
|
const err = await res.text();
|
|
|
|
|
|
throw new Error(`语音转文字失败: ${res.status} ${err}`);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const data = await res.json() as { text?: string };
|
|
|
|
|
|
return data.text || "";
|
|
|
|
|
|
}
|