Files
blog/write-server/src/lib/voice.ts
T
2026-06-22 14:59:24 +08:00

34 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 语音转文字:使用 OpenAI Whisper API 或其他兼容服务
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";
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 || "";
}