Skip to content

Instantly share code, notes, and snippets.

@jim60105
Last active February 4, 2025 07:00
Show Gist options
  • Save jim60105/baadfe06cf33878a94b510e35e3c4efb to your computer and use it in GitHub Desktop.
Save jim60105/baadfe06cf33878a94b510e35e3c4efb to your computer and use it in GitHub Desktop.
import { Args } from '@/runtime';
import { Input, Output } from '@/typings/edge_tts/edge_tts';
import { MsEdgeTTS, OUTPUT_FORMAT } from 'msedge-tts';
import internal from 'stream';
export async function handler({ input, logger }: Args<Input>): Promise<Output> {
const tts = new MsEdgeTTS();
await tts.setMetadata(input.voiceName, OUTPUT_FORMAT.WEBM_24KHZ_16BIT_MONO_OPUS);
const { audioStream } = await tts.toStream(input.text,{
pitch: input.pitch || "+0Hz",
rate: input.rate || "1.0",
volume: input.volume || "100.0",
});
return {
base64: await streamToBase64(audioStream),
};
}
/**
* Convert a Readable Stream to base64 string
* @param {ReadableStream} stream - a readable stream to convert in base64 string
* @returns {Promise} - Promise that resolve in a string containing the base64
*/
const streamToBase64 = (stream: internal.Readable): Promise<string> => {
const concat = require('concat-stream');
const { Base64Encode } = require('base64-stream');
return new Promise<string>((resolve, reject): string => {
const base64 = new Base64Encode();
const cbConcat = (base64) => {
resolve(base64);
};
return stream
.pipe(base64)
.pipe(concat(cbConcat))
.on('error', (error) => {
reject(error);
});
});
};
import { Args } from '@/runtime';
import { Input, Output } from '@/typings/edge_tts_with_upload/edge_tts_with_upload';
import { MsEdgeTTS, OUTPUT_FORMAT } from 'msedge-tts';
import { Catbox } from 'node-catbox';
import * as fs from 'fs';
import * as os from 'os';
export async function handler({ input, logger }: Args<Input>): Promise<Output> {
const tts = new MsEdgeTTS();
await tts.setMetadata(input.voiceName, OUTPUT_FORMAT.WEBM_24KHZ_16BIT_MONO_OPUS);
const { audioFilePath } = await tts.toFile(os.tmpdir(), input.text,{
pitch: input.pitch || "+0Hz",
rate: input.rate || "1.0",
volume: input.volume || "100.0",
});
try {
const catbox = new Catbox();
const response = await catbox.uploadFile({
path: audioFilePath
});
logger.info(response);
return { url: response };
} catch (err) {
logger.error(err); // -> error message from server
throw err;
} finally {
fs.unlinkSync(audioFilePath);
}
}
@jim60105
Copy link
Author

npm packages:

  • base64-stream
  • concat-stream
  • msedge-tts
  • node-catbox

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment