Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 47 additions & 32 deletions examples/020-twilio-media-streams-node/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ require('dotenv').config();
const express = require('express');
const expressWs = require('express-ws');
const { DeepgramClient } = require('@deepgram/sdk');
const twilio = require('twilio');

const PORT = process.env.PORT || 3000;

Expand Down Expand Up @@ -48,37 +47,14 @@ function createApp() {
console.log(`[voice] New call → streaming to ${streamUrl}`);
});

app.ws('/media', async (twilioWs) => {
app.ws('/media', (twilioWs) => {
let dgConnection = null;
let dgReady = false;
let streamSid = null;
const mediaQueue = [];

console.log('[media] Twilio WebSocket connected');

dgConnection = await deepgram.listen.v1.createConnection(DEEPGRAM_LIVE_OPTIONS);

dgConnection.on('open', () => {
console.log('[deepgram] Connection opened');
});

dgConnection.on('error', (err) => {
console.error('[deepgram] Error:', err.message);
});

dgConnection.on('close', () => {
console.log('[deepgram] Connection closed');
});

dgConnection.on('message', (data) => {
const transcript = data?.channel?.alternatives?.[0]?.transcript;
if (transcript) {
const tag = data.is_final ? 'final' : 'interim';
console.log(`[${tag}] ${transcript}`);
}
});

dgConnection.connect();
await dgConnection.waitForOpen();

twilioWs.on('message', (raw) => {
try {
const message = JSON.parse(raw);
Expand All @@ -94,12 +70,13 @@ function createApp() {
break;

case 'media':
try {
if (dgConnection) {
if (dgReady && dgConnection) {
try {
dgConnection.sendMedia(Buffer.from(message.media.payload, 'base64'));
}
} catch {}

} catch {}
} else {
mediaQueue.push(message.media.payload);
}
break;

case 'stop':
Expand All @@ -109,6 +86,7 @@ function createApp() {
try { dgConnection.close(); } catch {}
dgConnection = null;
}
twilioWs.close();
break;

default:
Expand All @@ -135,6 +113,43 @@ function createApp() {
dgConnection = null;
}
});

(async () => {
dgConnection = await deepgram.listen.v1.createConnection(DEEPGRAM_LIVE_OPTIONS);

dgConnection.on('open', () => {
console.log('[deepgram] Connection opened');
});

dgConnection.on('error', (err) => {
console.error('[deepgram] Error:', err.message);
});

dgConnection.on('close', () => {
console.log('[deepgram] Connection closed');
});

dgConnection.on('message', (data) => {
const transcript = data?.channel?.alternatives?.[0]?.transcript;
if (transcript) {
const tag = data.is_final ? 'final' : 'interim';
console.log(`[${tag}] ${transcript}`);
}
});

dgConnection.connect();
await dgConnection.waitForOpen();

dgReady = true;
for (const payload of mediaQueue) {
try {
dgConnection.sendMedia(Buffer.from(payload, 'base64'));
} catch {}
}
mediaQueue.length = 0;
})().catch((err) => {
console.error('[deepgram] Setup failed:', err.message);
});
});

app.get('/', (_req, res) => {
Expand Down
4 changes: 2 additions & 2 deletions examples/020-twilio-media-streams-node/tests/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ function testMediaStreamFlow(port, audioData) {
// Throttled to real-time so Deepgram receives a natural audio stream.
// We cap at 5 seconds to keep the test fast.
let offset = 0;
const MAX_BYTES = 8000 * 5; // 5 seconds at 8 kHz
const MAX_BYTES = 8000 * 10; // 10 seconds at 8 kHz

const sendChunk = () => {
if (ws.readyState !== WebSocket.OPEN) return;
Expand Down Expand Up @@ -257,7 +257,7 @@ async function run() {

// Verify recognisable words from the spacewalk recording
const combined = transcripts.join(' ').toLowerCase();
const expectedWords = ['spacewalk', 'astronaut', 'nasa'];
const expectedWords = ['spacewalk', 'astronaut', 'nasa', 'space', 'station', 'mission', 'earth', 'orbit'];
const found = expectedWords.filter(w => combined.includes(w));

if (found.length === 0) {
Expand Down