36 lines
1.3 KiB
TypeScript
36 lines
1.3 KiB
TypeScript
import { DEEPSEEK_API_KEY, DEEPSEEK_BASE_URL } from "@/lib/config";
|
||
|
||
// 语音转文字:使用 OpenAI Whisper API 或其他兼容服务
|
||
const WHISPER_API_KEY = process.env.WHISPER_API_KEY || DEEPSEEK_API_KEY || "";
|
||
const WHISPER_API_BASE = process.env.WHISPER_API_BASE || (DEEPSEEK_API_KEY ? 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 || "";
|
||
}
|