增加tts初步支持,大文件存储改用lfs
This commit is contained in:
1 parent
512651be68
commit
7df49b37f3
13 files changed
+159
-277
No files matched your search
@@ -0,0 +1,63 @@
|
||||
export interface TTS {
|
||||
say_all(content: string, voice: string): Promise<ArrayBuffer>;
|
||||
}
|
||||
|
||||
export class PiperCloudTTS {
|
||||
api_url: string;
|
||||
|
||||
constructor(api_url: string) {
|
||||
this.api_url = api_url;
|
||||
}
|
||||
|
||||
async say_all(content: string, voice: string): Promise<ArrayBuffer> {
|
||||
const response = await fetch(this.api_url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": "Mozilla/5.0",
|
||||
},
|
||||
body: JSON.stringify({ text: content, voice: voice }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(
|
||||
`Failed to fetch ${this.api_url}: ${response.status} ${response.statusText} - ${errorText}`,
|
||||
);
|
||||
}
|
||||
|
||||
return await response.arrayBuffer();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将长文本分段并直接流式写入文件
|
||||
*/
|
||||
async stream_to_file(
|
||||
content: string,
|
||||
voice: string,
|
||||
outputPath: string,
|
||||
chunkSize = 1000,
|
||||
): Promise<void> {
|
||||
const file = await Deno.open(outputPath, {
|
||||
write: true,
|
||||
create: true,
|
||||
truncate: true,
|
||||
});
|
||||
|
||||
try {
|
||||
for (let i = 0; i < content.length; i += chunkSize) {
|
||||
const chunk = content.slice(i, i + chunkSize);
|
||||
console.log(`Processing chunk ${i / chunkSize + 1}...`);
|
||||
|
||||
const audioData = await this.say_all(chunk, voice);
|
||||
// WAV 文件通常包含头。注意:如果只是简单合并 WAV,
|
||||
// 只有第一个 chunk 的头是有效的,后续 chunk 的头会被视为数据(可能会有杂音)。
|
||||
// 如果 API 返回的是原始 PCM,则没问题。
|
||||
// 这里我们先按照用户要求的流式写入实现。
|
||||
await file.write(new Uint8Array(audioData));
|
||||
}
|
||||
} finally {
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user