Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Getting Started with ElevenLabs Text-to-Speech API
Sanjay 🥷
Sanjay 🥷

Posted on • Edited on

     

Getting Started with ElevenLabs Text-to-Speech API

ElevenLabs: Advanced AI Speech Tool

ElevenLabs is an advanced AI speech tool that allows you to generate high-quality spoken audio in any voice and style. Their text-to-speech API is a service that developers can use to convert written text into speech in a variety of voices, including both pre-existing and custom voices.

With ElevenLabs, you can train your own voice model using your own recorded speech to create a custom voice for your application. The API is capable of rendering human-like intonation and inflections with unprecedented fidelity, resulting in speech that sounds natural and lifelike.

Getting Started with ElevenLabs API

To get started with the ElevenLabs API, you'll need to sign up for an API key on their websitehttps://beta.elevenlabs.io/. Once you've created an account click on your profile icon and go to profile settings there you can obtained an API key, you can start using their text-to-speech service.

Get the API key

Making a Basic Request

To make a basic request to the API, you'll need to send a POST request to their endpoint with your API key and the text you want to convert to speech. Here's an example of how to do this in javascript using the axios:

importaxiosfrom'axios';// Define a function called textToSpeech that takes in a string called inputText as its argument.consttextToSpeech=async(inputText)=>{// Set the API key for ElevenLabs API.// Do not use directly. Use environment variables.constAPI_KEY=ELEVEN_LABS_API_KEY;// Set the ID of the voice to be used.constVOICE_ID='21m00Tcm4TlvDq8ikWAM';// Set options for the API request.constoptions={method:'POST',url:`https://api.elevenlabs.io/v1/text-to-speech/${VOICE_ID}`,headers:{accept:'audio/mpeg',// Set the expected response type to audio/mpeg.'content-type':'application/json',// Set the content type to application/json.'xi-api-key':`${API_KEY}`,// Set the API key in the headers.},data:{text:inputText,// Pass in the inputText as the text to be converted to speech.},responseType:'arraybuffer',// Set the responseType to arraybuffer to receive binary data as response.};// Send the API request using Axios and wait for the response.constspeechDetails=awaitaxios.request(options);// Return the binary audio data received from the API response.returnspeechDetails.data;};// Export the textToSpeech function as the default export of this module.exportdefaulttextToSpeech;
Enter fullscreen modeExit fullscreen mode

Convert to audio file

Once you have received the audio data in the form of an ArrayBuffer from the ElevenLabs API, you can convert it into an MP3 blob file that can be played or saved. Here's how to do it in React js:

import{useState,useEffect}from'react';constAudioPlayer=()=>{// Define a state variable to hold the audio URLconst[audioURL,setAudioURL]=useState(null);// Define a function to fetch the audio data and set the URL state variableconsthandleAudioFetch=async()=>{// Call the textToSpeech function to generate the audio data for the text "Hello welcome"constdata=awaittextToSpeech("Hello welcome")// Create a new Blob object from the audio data with MIME type 'audio/mpeg'constblob=newBlob([data],{type:'audio/mpeg'});// Create a URL for the blob objectconsturl=URL.createObjectURL(blob);// Set the audio URL state variable to the newly created URLsetAudioURL(url);};// Use the useEffect hook to call the handleAudioFetch function once when the component mountsuseEffect(()=>{handleAudioFetch()},[]);// Render an audio element with the URL if it is not nullreturn(<div>{audioURL&&(<audioautoPlaycontrols><sourcesrc={audioURL}type="audio/mpeg"/></audio>)}</div>);};exportdefaultAudioPlayer;
Enter fullscreen modeExit fullscreen mode

For more detailed documentation on how to use ElevenLabs' API, you can visit their API documentation page athttps://api.elevenlabs.io/docs#/ where you can try it out the API.

Top comments(6)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
greg_cf3a672509a4 profile image
Greg
  • Joined

Would this approach expose your api key?

CollapseExpand
 
thecmdrunner profile image
Pranav
Shipping quality apps • Keeping it simple
  • Email
  • Location
    India
  • Education
    GGS Polytechnic
  • Pronouns
    He/him
  • Work
    Full Stack Developer (Freelance)
  • Joined

Yes, this will include the API key in your frontend code. You should instead create an API endpoint or use Server Actions (if you're using nextjs) for this.

CollapseExpand
 
ssk14 profile image
Sanjay 🥷
I'm a Full stack ninja crafting innovative solutions for real-world impact. Passionate about user-centric applications and driving business through technology.
  • Location
    Chennai, India
  • Education
    PSG College Of Technology
  • Work
    Developer | Consultant @thoughtworks
  • Joined

Hello@greg, we should always use API key as environment variables in .env files.

CollapseExpand
 
msopacua profile image
msopacua
Python Engineer. Frontend Capable. Cloud proficient.
  • Joined

That doesn't help. The variables will be exposed, since the build process will include them in the generated bundle. Dotenv only prevents it to be exposed to the git repository.

CollapseExpand
 
dennis_newton profile image
Dennis
I know Frontend Development and wanna learn more about this web3 bubble. I am carving my way to become the best blockchain dev and I want to support my fellow programmers.
  • Education
    Techno
  • Work
    Student
  • Joined

Hello Can you please help me. I am trying to upload an audio file instead of text with the "input_audio" param which essentially takes a audio public url. But no mateer how many times I give a downlodable url, it shows "invalid audio url"
Can you please help!!!!

CollapseExpand
 
robadkerson profile image
RobAdkerson
  • Joined

Any way to get the audio in a different file format (wav) or frame rate?

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I'm a Full stack ninja crafting innovative solutions for real-world impact. Passionate about user-centric applications and driving business through technology.
  • Location
    Chennai, India
  • Education
    PSG College Of Technology
  • Work
    Developer | Consultant @thoughtworks
  • Joined

More fromSanjay 🥷

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp