Skip to main content

SDK Quick Start

Get up and running with Kaltura Avatar in 5 minutes using SDK-based control.

Best For

This approach is perfect for demos, prototypes, and learning. For production applications, see API Quick Start.

Step 1: Install the SDK

npm install @unisphere/models-sdk-js

Step 2: Get Your Kaltura Session (KS)

You'll need a Kaltura Session to authenticate with the Avatar API.

Generate a KS: Follow the Kaltura Session Creation Guide

Security

Never expose your Kaltura Session in client-side code for production applications. For production, use the API-based approach where the KS stays on your server.

Step 3: Prepare Your HTML

Create a container div where the avatar will be displayed:

<!DOCTYPE html>
<html>
<head>
<title>Kaltura Avatar Demo</title>
<style>
#avatar-container {
width: 512px;
height: 512px;
border: 2px solid #ccc;
border-radius: 8px;
overflow: hidden;
}
</style>
</head>
<body>
<h1>Kaltura Avatar Demo</h1>

<!-- Avatar will be displayed here -->
<div id="avatar-container"></div>

<div style="margin-top: 20px;">
<button id="speak-btn">Make Avatar Speak</button>
<button id="interrupt-btn">Interrupt</button>
<button id="end-btn">End Session</button>
</div>

<script src="main.js" type="module"></script>
</body>
</html>

Step 4: Create the Avatar Session

Create a file named main.js:

import { KalturaAvatarSession } from '@unisphere/models-sdk-js';

// Create SDK instance with your Kaltura Session
const session = new KalturaAvatarSession('your-kaltura-session-here', {
baseUrl: 'https://api.avatar.us.kaltura.ai/v1/avatar-session',
});

// Setup event listeners
session.on('stateChange', (state) => {
console.log('Session state:', state);
});

session.on('connectionChange', (state) => {
console.log('Connection state:', state);
});

session.on('error', (error) => {
console.error('Error:', error.message);
});

// Create session with auto-attach
async function startAvatar() {
try {
await session.createSession({
avatarId: 'avatar-123',
voiceId: 'voice-456', // optional
videoContainerId: 'avatar-container', // Auto-attach video element
});

console.log('Avatar session started!');
console.log('Session ID:', session.getSessionId());

// Make avatar speak
await session.sayText('Hello! I am your Kaltura Avatar. How can I help you today?');
} catch (error) {
console.error('Failed to start avatar:', error);
}
}

// Button handlers
document.getElementById('speak-btn').addEventListener('click', async () => {
await session.sayText('This is a test message from the avatar.');
});

document.getElementById('interrupt-btn').addEventListener('click', async () => {
await session.interrupt();
console.log('Avatar interrupted');
});

document.getElementById('end-btn').addEventListener('click', async () => {
await session.endSession();
console.log('Session ended');
});

// Start the avatar when page loads
startAvatar();
API Key Security

This example includes the API key in client code. This is OK for demos but NOT for production. For production apps, use API-based control.

Step 4: Run Your Application

If using a bundler like Vite or Webpack:

npm run dev

If using vanilla JavaScript, serve with any static server:

npx serve .

Open your browser and you should see the avatar!

What Just Happened?

  1. Created SDK instance with your Kaltura Session and base URL
  2. Created avatar session with avatarId and videoContainerId
  3. SDK automatically:
    • Called the backend to create a session using your Kaltura Session
    • Established WebRTC connection
    • Created video element inside the container
    • Started keep-alive (every 10 seconds)
  4. Made avatar speak using sayText()

SDK-Only vs Backend-Created Sessions

This quick start uses SDK-only control where the SDK itself creates the session. There's also a BE/FE split approach where your backend creates the session:

AspectSDK-OnlyBackend-Created
Who creates sessionSDK (browser)Your backend server
apiKey needed✅ Yes, in client code❌ No, backend has it
Constructornew KalturaAvatarSession('your-ks')new KalturaAvatarSession() (no apiKey)
InitializationcreateSession()initSession({sessionId, token})
Security⚠️ Kaltura Session exposed✅ Kaltura Session hidden
Best forDemos, internal toolsProduction apps

Switching to Backend-Created Sessions

To use backend-created sessions (recommended for production):

// Frontend - no apiKey needed
const session = new KalturaAvatarSession(undefined, {
baseUrl: 'https://api.avatar.us.kaltura.ai/v1/avatar-session',
});

// Get session from your backend
const { sessionId, token } = await fetch('/api/create-avatar-session').then(r => r.json());

// Initialize with backend-provided credentials
await session.initSession(
{ sessionId, token },
{ videoContainerId: 'avatar-container' }
);

// Rest is the same
await session.sayText('Hello!');

See API Quick Start for the complete backend setup.

Common Issues

Avatar not displaying

Check browser console for errors. Common causes:

  • Invalid API key
  • Incorrect baseUrl
  • WebRTC not supported in browser
  • Firewall blocking WebRTC

Video element not found

Make sure the container exists before calling createSession():

// Wrong - container might not exist yet
await session.createSession({ videoContainerId: 'avatar-container' });

// Right - wait for DOM
document.addEventListener('DOMContentLoaded', async () => {
await session.createSession({ videoContainerId: 'avatar-container' });
});

Connection timeout

  • Check network connectivity
  • Verify TURN servers are accessible

Next Steps

Now that you have a working avatar:

Learn More About the SDK

Explore Examples

Ready for Production?

Complete Working Example

import { KalturaAvatarSession, SessionState, AvatarError } from '@unisphere/models-sdk-js';

async function runAvatarDemo() {
const session = new KalturaAvatarSession('your-api-key', {
baseUrl: 'https://api.avatar.us.kaltura.ai/v1/avatar-session',
logLevel: 'info',
});

// Event listeners
session.on('stateChange', (state: SessionState) => {
console.log('State changed:', state);
document.getElementById('status').textContent = state;
});

session.on('error', (error: AvatarError) => {
console.error('SDK Error:', error.code, error.message);
alert(`Error: ${error.message}`);
});

try {
// Create and attach
await session.createSession({
avatarId: 'avatar-123',
voiceId: 'voice-456',
videoContainerId: 'avatar-container',
});

console.log('✅ Avatar ready!');
console.log('Session ID:', session.getSessionId());

// Welcome message
await session.sayText('Welcome to Kaltura Avatar! I am ready to help you.');

// Interactive demo
const speakBtn = document.getElementById('speak-btn');
speakBtn.onclick = async () => {
await session.sayText('You clicked the speak button. This is a demo message.');
};
} catch (error) {
if (error instanceof AvatarError) {
console.error('Avatar Error:', error.code, error.message);
} else {
console.error('Unexpected error:', error);
}
}
}

// Start when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', runAvatarDemo);
} else {
runAvatarDemo();
}

Troubleshooting

See the Troubleshooting Guide for detailed solutions to common issues.