Skip to content

Instantly share code, notes, and snippets.

@SimplGy
Created May 22, 2023 00:36
Show Gist options
  • Save SimplGy/7532c1c892187b5001e685f0673b5b18 to your computer and use it in GitHub Desktop.
Save SimplGy/7532c1c892187b5001e685f0673b5b18 to your computer and use it in GitHub Desktop.
works, but only for short strings. getting 400 on anything else.
// docs:
// https://docs.elevenlabs.io/api-reference/quick-start/introduction
// https://api.elevenlabs.io/docs#/text-to-speech/Text_to_speech_v1_text_to_speech__voice_id__post
const axios = require('axios');
const fs = require('fs');
const path = require('path');
require('dotenv').config();
const API_KEY = process.env.ELEVENLABS_API_KEY;
if (API_KEY == null) return console.error('Please set env variable ELEVENLABS_API_KEY');
const VOICE_ID = 'ErXwobaYiN019PkySvjV'; // "Antoni"
const outputAudioFile = './audio.mp3');
// DO IT!
makeAudioFileFromText('5 Cool goats drink aliens. 7 Drunk apes eat batteries. 10 Fat cats go dancing.', outputAudioFile); // works!
// -------------------------------------------------------------- lib
async function makeAudioFileFromText(text, filename) {
try {
console.log(`Success, Audio saved as: ${filename}`);
} catch (error) {
console.error(`An error occurred while converting text to speech: ${error}`);
}
try {
var voice = "https://api.elevenlabs.io/v1/text-to-speech/" + VOICE_ID + "/stream";
fs.open(filename, 'w', (error, fd) => {
if (error) {
console.error('An error occurred while creating the file:', error);
return;
}
});
const response = await axios({
method: 'post',
url: voice,
data: { text },
headers: {
'Accept': 'audio/mpeg',
'xi-api-key': API_KEY,
'Content-Type': 'application/json',
},
responseType: 'stream'
});
response.data.pipe(fs.createWriteStream(filename));
} catch (error) {
console.error(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment