Skip to main content
Last verified: 2026-06-08
Use Twilio Programmable Voice with Media Streams so a phone call receives audio generated by Cartesia TTS over WebSockets. This walkthrough uses Node.js: a small server bridges Twilio’s stream to Cartesia and plays TTS audio on the callee’s line.

Prerequisites

Before you begin, make sure you have the following:
  1. Node.js installed.
  2. A Twilio account. You will need your Account SID and Auth Token.
  3. A Cartesia API key.
  4. A phone number that you want to call.
  5. A Twilio phone number to call from.
  6. An ngrok authtoken (a free account works).

Get Started

1

Set Up Your Project

  1. Create a new directory for your project and navigate to it in your terminal.
  2. Initialize a new Node.js project:
  3. Install the required dependencies:
2

Configure Environment Variables

Create a .env file in your project root and add the following:
Replace the placeholder values with your actual credentials.
3

Create the Main Script

Create a file named app.js (or any name you prefer) and add the following code:
4

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:
5

Set Up Twilio Calling

Configure your Twilio outbound and inbound numbers:
6

Implement Main Logic

The main() function orchestrates the entire process:
  1. Connects to the Cartesia TTS WebSocket
  2. Tests the TTS WebSocket
  3. Sets up a Twilio WebSocket server
  4. Creates an ngrok tunnel for the Twilio WebSocket
  5. Initiates the call using Twilio
7

Run the Application

To run the application, use the following command:

How It Works

  1. The script establishes a connection to Cartesia’s TTS WebSocket.
  2. It sets up a local WebSocket server to communicate with Twilio.
  3. An ngrok tunnel is created to expose the local WebSocket server to the internet.
  4. A call is initiated using Twilio, connecting to the ngrok tunnel.
  5. When the call connects, the script sends the predefined message to Cartesia’s TTS.
  6. Cartesia converts the text to speech and sends audio chunks back.
  7. 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.
  • If you see invalid tunnel configuration, make sure you’re using the better supported @ngrok/ngrok package and not ngrok.