37 lines
1.4 KiB
TypeScript
37 lines
1.4 KiB
TypeScript
import { existsSync, mkdirSync } from "node:fs";
|
|
import { writeFile } from "node:fs/promises";
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
import { EdgeTTS } from "edge-tts-universal";
|
|
import { getAudioFilePath, getAudioPublicPath } from "@/lib/audio";
|
|
|
|
export const runtime = "nodejs";
|
|
export const dynamic = "force-dynamic";
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const body = await request.json();
|
|
const voice = String(body.voice ?? "en-US-EmmaMultilingualNeural");
|
|
const rate = String(body.rate ?? "-10%");
|
|
const text = String(body.text ?? "Hello, welcome to English PK.");
|
|
|
|
const audioDirectory = getAudioFilePath("preview");
|
|
if (!existsSync(audioDirectory)) {
|
|
mkdirSync(audioDirectory, { recursive: true });
|
|
}
|
|
|
|
const fileName = `tts-preview-${Date.now()}.mp3`;
|
|
const filePath = getAudioFilePath("preview", fileName);
|
|
const publicPath = getAudioPublicPath(`preview/${fileName}`);
|
|
|
|
const tts = new EdgeTTS(text, voice, { rate });
|
|
const result = await tts.synthesize();
|
|
const audioBuffer = Buffer.from(await result.audio.arrayBuffer());
|
|
await writeFile(filePath, audioBuffer);
|
|
|
|
return NextResponse.json({ audio: publicPath });
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : "试听语音失败";
|
|
return NextResponse.json({ message }, { status: 500 });
|
|
}
|
|
}
|