-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (64 loc) · 2.09 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Run ./api.js if you want to use a server!
*/
import { readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { randomUUID } from 'node:crypto'
import * as TTS from '@sefinek/google-tts-api'
import Ffmpeg from 'fluent-ffmpeg'
export default async function main(payload, tmp = '', ffmpegPath = '') {
const { text, lang = 'en', speed, pitch = 1 } = payload
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': '*',
'Cache-Control': 'public, max-age=31536000, immutable'
}
if (!text || !text.length) {
return new Response(await readFile('./README.md'), {
status: 200,
statusText: '`text` is missing',
headers: {
'content-type': 'text/html; charset=utf-8',
...headers
}
})
}
const audios = await TTS.getAllAudioBase64(text, { lang })
const ffmpeg = Ffmpeg()
const files = []
if (ffmpegPath.length) ffmpeg.setFfmpegPath(ffmpegPath)
for (const { base64 } of audios) {
const path = join(tmp, `${randomUUID()}.mp3`)
const buffer = Buffer.from(base64, 'base64')
files.push(path)
ffmpeg.addInput(path)
await writeFile(path, buffer)
}
const sample = 44100
const setrate = sample * pitch
const tempo = speed || (1 + (1 - pitch))
const chunks = []
await new Promise((resolve, reject) => ffmpeg
.complexFilter([
{ filter: 'concat', options: { n: files.length, v: 0, a: 1 }, outputs: 'merged' },
{ filter: 'aresample', options: sample, inputs: 'merged', outputs: 'resampled' },
{ filter: 'asetrate', options: setrate, inputs: 'resampled', outputs: 'rated' },
{ filter: 'atempo', options: tempo, inputs: 'rated', outputs: 'final' },
])
.outputOptions('-map [final]')
.on('end', resolve)
.on('error', reject)
.outputFormat('mp3')
.pipe()
.on('data', chunk => chunks.push(chunk))
)
return new Response(Buffer.concat(chunks), {
status: 200,
headers: {
'content-type': 'audio/mp3',
'content-disposition': 'inline',
...headers
}
})
}