Back to all functions

Generate Voice Responses via ElevenLabs API

Functions
1

Retrieve voice responses and audio data from ElevenLabs using text inputs (voice projects only).

Created By
Nicolas Arcay Bermejo
Voiceflow
download-icon
INPUT VARIABLES
{
VoiceID
}
Voice ID from ElevenLabs
{
Text
}
Text to convert
{
ElevenLabsAPIKey
}
ElevenLabs API Key
{
}
{
}
{
}
share-icon
OUTPUT VARIABLES
{
audioDataURI
}
{
}
{
}
{
}
{
}
{
}
paths-icon
PATHS
{
error
}
error path
{
default
}
default path
{
}
{
}
{
}
{
}

Function Walkthrough

Function Code Snippet

 
export default async function main(args) {
    const { VoiceID: inputVoiceID, Text, ElevenLabsAPIKey } = args.inputVars
    let VoiceID = inputVoiceID;

    try {
        if (!ElevenLabsAPIKey) {
            return {
                outputVars: {
                    error: `Need an ElevenLabs API Key`
                },
                next: {
                    path: 'error'
                },
                trace: [
                    {
                        type: 'debug',
                        payload: {
                            message: `Need an ElevenLabs API Key`
                        }
                    }
                ],
            }
        }

        if (!Text) {
            return {
                outputVars: {
                    error: `Need a text to convert`
                },
                next: {
                    path: 'error'
                },
                trace: [
                    {
                        type: 'debug',
                        payload: {
                            message: `Need a text to convert`
                        }
                    }
                ],
            }
        }

        if (!VoiceID) {
            VoiceID = '21m00Tcm4TlvDq8ikWAM'
        }

        const response = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${VoiceID}`,
            {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    accept: 'audio/mpeg',
                    'xi-api-key': `${ElevenLabsAPIKey}`
                },
                body: JSON.stringify({
                    text: Text,
                    model_id: 'eleven_multilingual_v2'
                })
            },
            { parseType: 'arrayBuffer' }
        );

        if (!response.ok) {
            return {
                next: {
                    path: 'error'
                },
                trace: [
                    {
                        type: 'debug',
                        payload: {
                            message: `Error with ElevenLabs API`
                        }
                    }
                ],
            }
        }

        let uint8Array = new Uint8Array(response.arrayBuffer);
        let binaryString = Array.prototype.map.call(uint8Array, function (byte) {
            return String.fromCharCode(byte);
        }).join('');

        function toBase64(input) {
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
            let str = '';
            let padding = (input.length % 3);
            for (let i = 0; i < input.length; i += 3) {
                let a = input.charCodeAt(i);
                let b = input.charCodeAt(i + 1);
                let c = input.charCodeAt(i + 2);
                str += chars[a >> 2];
                str += chars[((a & 3) << 4) | (b >> 4)];
                str += chars[((b & 15) << 2) | (c >> 6)];
                str += chars[c & 63];
            }
            return padding ? str.slice(0, padding - 3) + '==='.substring(padding) : str;
        }

        let base64Audio = toBase64(binaryString);
        const audioData = `data:audio/mpeg;base64,${base64Audio}`

        return {
            outputVars: {
                audioDataURI: audioData
            },
            next: {
                path: 'success'
            },
            trace: [
                {
                    type: 'debug',
                    payload: {
                        message: `Successfully converted the text`
                    }
                },
                {
                    type: 'audio',
                    payload: {
                        src: audioData
                    }
                }
            ],
        }

    } catch (error) {
        return {
            outputVars: {
                error: error
            },
            next: {
                path: 'error'
            },
            trace: [
                {
                    type: 'debug',
                    payload: {
                        message: error
                    }
                }
            ],
        }
    }
}
copy-icon

Have something to share?

Share your creation with over 250,000 other global Voiceflow users.

ghraphic
No items found.