Integrate with Twilio
How to integrate Twilio with Cartesia to generate audio from text and send it as a voice call.
This guide will walk you through the process of integrating Cartesia’s Text-to-Speech (TTS) API with Twilio’s calling capabilities. By following these steps, you’ll be able to create an application that initiates phone calls and uses Cartesia’s TTS to speak to the call recipient.
Prerequisites
Before you begin, make sure you have the following:
- Node.js installed.
- A Twilio account. You will need your Account SID and Auth Token.
- A Cartesia API key.
- A phone number that you want to call.
- A Twilio phone number to call from.
Get Started
Set Up Your Project
- Create a new directory for your project and navigate to it in your terminal.
- Initialize a new Node.js project:
- Install the required dependencies:
Configure Environment Variables
Create a .env
file in your project root and add the following:
Replace the placeholder values with your actual credentials.
Create the Main Script
Create a file named app.js
(or any name you prefer) and add the following code:
Configure Cartesia TTS
In the script, you’ll find a configuration section for Cartesia TTS. Make sure to set the following variables according to your needs:
How It Works
- The script establishes a connection to Cartesia’s TTS WebSocket.
- It sets up a local WebSocket server to communicate with Twilio.
- An ngrok tunnel is created to expose the local WebSocket server to the internet.
- A call is initiated using Twilio, connecting to the ngrok tunnel.
- When the call connects, the script sends the predefined message to Cartesia’s TTS.
- Cartesia converts the text to speech and sends audio chunks back.
- The script forwards these audio chunks to Twilio, which plays them on the call.
Customization
- To change the spoken message, modify the
partialResponse
variable. - Adjust the voice parameters in the
voice
object to change the TTS voice characteristics. - Modify the
audioChunksReceived
threshold to control when the call should end.
Troubleshooting
- If you encounter any issues, check the console logs for detailed error messages.
- Ensure all required environment variables are correctly set.
- Verify that your Twilio and Cartesia credentials are valid and have the necessary permissions.