-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_avatar_interface.html
More file actions
792 lines (675 loc) · 31.7 KB
/
test_avatar_interface.html
File metadata and controls
792 lines (675 loc) · 31.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Echo Mind Avatar Test Interface</title>
<script src="https://unpkg.com/livekit-client@1.15.13/dist/livekit-client.umd.js"></script>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
min-height: 100vh;
}
.container {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 20px;
padding: 30px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
margin-bottom: 30px;
font-size: 2.5em;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
.status {
text-align: center;
padding: 15px;
border-radius: 10px;
margin-bottom: 20px;
font-weight: bold;
}
.status.disconnected {
background: rgba(255, 0, 0, 0.2);
border: 2px solid #ff4444;
}
.status.connected {
background: rgba(0, 255, 0, 0.2);
border: 2px solid #44ff44;
}
.controls {
display: flex;
gap: 15px;
justify-content: center;
margin-bottom: 30px;
flex-wrap: wrap;
}
button {
padding: 15px 30px;
border: none;
border-radius: 25px;
font-size: 16px;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
}
.record-btn {
background: linear-gradient(45deg, #ff6b6b, #ee5a24);
color: white;
}
.record-btn.recording {
background: linear-gradient(45deg, #ff3838, #c0392b);
animation: pulse 1s infinite;
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
}
.test-btn {
background: linear-gradient(45deg, #4ecdc4, #44a08d);
color: white;
}
.clear-btn {
background: linear-gradient(45deg, #ffa726, #ff7043);
color: white;
}
.test-input {
width: 100%;
padding: 15px;
border: none;
border-radius: 10px;
font-size: 16px;
margin-bottom: 15px;
background: rgba(255, 255, 255, 0.9);
color: #333;
}
.conversation {
background: rgba(255, 255, 255, 0.1);
border-radius: 15px;
padding: 20px;
max-height: 400px;
overflow-y: auto;
margin-bottom: 20px;
}
.message {
margin-bottom: 15px;
padding: 10px 15px;
border-radius: 10px;
word-wrap: break-word;
}
.user-message {
background: rgba(100, 200, 255, 0.3);
margin-left: 20px;
}
.avatar-message {
background: rgba(255, 255, 255, 0.2);
margin-right: 20px;
}
.tool-execution {
background: rgba(255, 200, 100, 0.3);
font-size: 0.9em;
font-style: italic;
margin: 5px 0;
}
.transcript {
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
padding: 15px;
margin-bottom: 20px;
min-height: 50px;
}
.interim {
color: #ccc;
font-style: italic;
}
.final {
color: white;
font-weight: bold;
}
.suggestions {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin-bottom: 20px;
}
.suggestion {
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.3);
color: white;
padding: 8px 15px;
border-radius: 20px;
cursor: pointer;
font-size: 14px;
transition: all 0.3s ease;
}
.suggestion:hover {
background: rgba(255, 255, 255, 0.3);
transform: translateY(-1px);
}
</style>
</head>
<body>
<div class="container">
<h1>🎭 Echo Mind Avatar Test</h1>
<div id="status" class="status disconnected">
🔴 Disconnected - Click Connect to start
</div>
<!-- HeyGen Avatar Video Container -->
<div class="avatar-container" style="text-align: center; margin: 20px 0; background: rgba(0,0,0,0.3); border-radius: 15px; padding: 20px;">
<div id="avatarVideo" style="width: 400px; height: 300px; margin: 0 auto; background: #000; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: #666;">
<div id="avatarPlaceholder">🎭 Avatar will appear here when connected</div>
</div>
<div id="avatarStatus" style="margin-top: 10px; font-size: 14px; color: #ccc;">
Avatar Status: Not initialized
</div>
</div>
<div class="controls">
<button id="connectBtn" onclick="connect()">Connect to Avatar</button>
<button id="recordBtn" class="record-btn" onclick="toggleRecording()" disabled>🎤 Microphone (Auto-starts)</button>
<button class="clear-btn" onclick="clearConversation()">Clear Chat</button>
</div>
<div class="suggestions">
<div class="suggestion" onclick="sendTestMessage('Hello, I am testing the Echo Mind system')">👋 English: Hello</div>
<div class="suggestion" onclick="sendTestMessage('Hola, ¿cómo estás? Soy Echo Mind')">🇪🇸 Spanish: Hola</div>
<div class="suggestion" onclick="sendTestMessage('Bonjour, comment allez-vous?')">🇫🇷 French: Bonjour</div>
<div class="suggestion" onclick="sendTestMessage('Guten Tag, wie geht es Ihnen?')">🇩🇪 German: Guten Tag</div>
<div class="suggestion" onclick="sendTestMessage('Ciao, come stai?')">🇮🇹 Italian: Ciao</div>
<div class="suggestion" onclick="sendTestMessage('What time is it?')">⏰ Ask Time</div>
<div class="suggestion" onclick="sendTestMessage('Search for latest AI news')">🔍 Web Search</div>
<div class="suggestion" onclick="sendTestMessage('Remember that I like programming')">💾 Test Memory</div>
</div>
<input type="text" id="testInput" class="test-input" placeholder="Type a message to test (or use voice recording)" onkeypress="handleKeyPress(event)">
<button class="test-btn" onclick="sendTextMessage()">Send Text Message</button>
<div class="transcript">
<strong>Live Transcript:</strong>
<div id="transcript">Connect to avatar to start hands-free voice interaction...</div>
</div>
<div class="conversation" id="conversation">
<div class="message avatar-message">
<strong>Echo Mind:</strong> Hello! I'm ready to chat. Try asking me about the time, searching the web, or just having a conversation. I'll remember what we talk about!
</div>
</div>
</div>
<script>
let ws = null;
let isRecording = false;
let mediaRecorder = null;
let audioStream = null;
let heygenSessionId = null;
let avatarVideoElement = null;
let liveKitRoom = null;
let liveKitConnectionDetails = null;
let isLiveKitConnected = false;
let remoteAudioElements = new Map();
async function connect() {
const status = document.getElementById('status');
const connectBtn = document.getElementById('connectBtn');
const recordBtn = document.getElementById('recordBtn');
try {
// First, create HeyGen session
await createHeyGenSession();
// Then connect WebSocket
ws = new WebSocket('ws://localhost:8000/ws/audio');
ws.onopen = async () => {
status.className = 'status connected';
status.innerHTML = '🟢 Connected to Echo Mind Avatar';
connectBtn.textContent = 'Disconnect';
connectBtn.onclick = disconnect;
recordBtn.disabled = false;
addMessage('System', 'Connected to Echo Mind Avatar! Ready for voice or text input.', 'avatar-message');
// Start HeyGen session
if (heygenSessionId) {
await startHeyGenSession();
// Auto-start microphone recording after successful connection
setTimeout(async () => {
addMessage('System', '🎤 Auto-starting microphone for hands-free interaction...', 'avatar-message');
await startRecording();
}, 2000); // Wait 2 seconds for everything to be ready
}
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
handleWebSocketMessage(data);
};
ws.onclose = () => {
status.className = 'status disconnected';
status.innerHTML = '🔴 Disconnected';
connectBtn.textContent = 'Connect to Avatar';
connectBtn.onclick = connect;
recordBtn.disabled = true;
addMessage('System', 'Disconnected from avatar.', 'avatar-message');
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
addMessage('System', 'Connection error. Make sure the backend server is running on localhost:8000', 'avatar-message');
};
} catch (error) {
console.error('Connection failed:', error);
addMessage('System', 'Failed to connect. Is the server running?', 'avatar-message');
}
}
async function disconnect() {
if (ws) {
ws.close();
}
if (isRecording) {
stopRecording();
}
// Close HeyGen session
if (heygenSessionId) {
await closeHeyGenSession();
}
}
async function handleWebSocketMessage(data) {
switch (data.type) {
case 'interim_transcript':
updateTranscript(data.text, false);
break;
case 'enhanced_text':
updateTranscript('', true); // Clear transcript
// Show detected language if available
let responseText = data.text;
if (data.detected_language) {
addMessage('System', `🌍 Language detected: ${data.detected_language.toUpperCase()}`, 'avatar-message');
}
addMessage('Echo Mind', responseText, 'avatar-message');
if (data.tool_executions && data.tool_executions.length > 0) {
data.tool_executions.forEach(tool => {
addMessage('Tool', `🛠️ ${tool.tool_name}: ${tool.result}`, 'tool-execution');
});
}
// Send text to HeyGen avatar for speech
if (heygenSessionId && data.text) {
await sendToHeyGenAvatar(data.text);
}
break;
case 'debug_stats':
console.log('Debug stats:', data.stats);
break;
}
}
function updateTranscript(text, isFinal) {
const transcript = document.getElementById('transcript');
if (isFinal) {
transcript.innerHTML = 'Listening... speak to interact with the avatar';
} else {
transcript.innerHTML = `<span class="interim">${text}</span>`;
}
}
async function toggleRecording() {
if (!isRecording) {
await startRecording();
} else {
stopRecording();
}
}
async function startRecording() {
try {
audioStream = await navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: 16000,
channelCount: 1,
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
}
});
// Use Web Audio API for proper PCM conversion
const audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: 16000
});
const source = audioContext.createMediaStreamSource(audioStream);
const processor = audioContext.createScriptProcessor(4096, 1, 1);
processor.onaudioprocess = (event) => {
if (ws && ws.readyState === WebSocket.OPEN) {
const inputBuffer = event.inputBuffer;
const inputData = inputBuffer.getChannelData(0);
// Convert Float32 to Int16 PCM (exactly what backend expects)
const pcmData = new Int16Array(inputData.length);
for (let i = 0; i < inputData.length; i++) {
pcmData[i] = Math.max(-32768, Math.min(32767, inputData[i] * 32768));
}
// Send raw PCM data as binary
ws.send(pcmData.buffer);
}
};
source.connect(processor);
processor.connect(audioContext.destination);
isRecording = true;
const recordBtn = document.getElementById('recordBtn');
recordBtn.textContent = '🛑 Stop Recording';
recordBtn.classList.add('recording');
addMessage('System', '🎤 Microphone active - speak naturally to interact with avatar!', 'avatar-message');
updateTranscript('Listening... speak to interact with the avatar', false);
// Store for cleanup
audioStream.processor = processor;
audioStream.audioContext = audioContext;
} catch (error) {
console.error('Failed to start recording:', error);
addMessage('System', 'Failed to access microphone. Please grant permission and try again.', 'avatar-message');
// Show user-friendly error message
if (error.name === 'NotAllowedError') {
addMessage('System', '❌ Microphone permission denied. Please allow microphone access in your browser settings.', 'avatar-message');
} else if (error.name === 'NotFoundError') {
addMessage('System', '❌ No microphone found. Please connect a microphone and try again.', 'avatar-message');
} else {
addMessage('System', `❌ Microphone error: ${error.message}`, 'avatar-message');
}
}
}
function stopRecording() {
if (audioStream) {
// Clean up Web Audio API
if (audioStream.processor) {
audioStream.processor.disconnect();
}
if (audioStream.audioContext) {
audioStream.audioContext.close();
}
// Stop media tracks
audioStream.getTracks().forEach(track => track.stop());
}
isRecording = false;
const recordBtn = document.getElementById('recordBtn');
recordBtn.textContent = '🎤 Microphone (Auto-starts)';
recordBtn.classList.remove('recording');
addMessage('System', '🛑 Recording stopped', 'avatar-message');
updateTranscript('Connect to avatar to start hands-free voice interaction...', true);
}
function sendTextMessage() {
const input = document.getElementById('testInput');
const message = input.value.trim();
if (message && ws && ws.readyState === WebSocket.OPEN) {
sendTestMessage(message);
input.value = '';
}
}
function sendTestMessage(message) {
if (ws && ws.readyState === WebSocket.OPEN) {
addMessage('You', message, 'user-message');
ws.send(JSON.stringify({
type: 'test_text',
text: message
}));
} else {
addMessage('System', 'Not connected to avatar. Click Connect first.', 'avatar-message');
}
}
function handleKeyPress(event) {
if (event.key === 'Enter') {
sendTextMessage();
}
}
function addMessage(sender, message, className) {
const conversation = document.getElementById('conversation');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${className}`;
messageDiv.innerHTML = `<strong>${sender}:</strong> ${message}`;
conversation.appendChild(messageDiv);
conversation.scrollTop = conversation.scrollHeight;
}
function clearConversation() {
const conversation = document.getElementById('conversation');
conversation.innerHTML = `
<div class="message avatar-message">
<strong>Echo Mind:</strong> Conversation cleared! Ready for new interactions.
</div>
`;
}
// HeyGen Integration Functions
async function createHeyGenSession() {
try {
updateAvatarStatus('Creating HeyGen session...');
const response = await fetch('http://localhost:8000/api/v1/heygen/session/new', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('HeyGen session created:', data);
if (data.session_id) {
heygenSessionId = data.session_id;
// Store LiveKit connection details
liveKitConnectionDetails = {
session_id: data.session_id,
livekit_url: data.livekit_url,
livekit_token: data.livekit_token
};
updateAvatarStatus('HeyGen session created');
addMessage('System', 'HeyGen session created successfully!', 'avatar-message');
} else {
throw new Error('No session ID received from HeyGen');
}
} catch (error) {
console.error('Failed to create HeyGen session:', error);
updateAvatarStatus('Failed to create avatar session');
addMessage('System', `Failed to create avatar session: ${error.message}`, 'avatar-message');
}
}
async function startHeyGenSession() {
if (!heygenSessionId) return;
try {
updateAvatarStatus('Starting avatar session...');
const response = await fetch(`http://localhost:8000/api/v1/heygen/session/${heygenSessionId}/start`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('HeyGen session started:', data);
updateAvatarStatus('Avatar session active');
addMessage('System', 'HeyGen session started! Connecting to LiveKit...', 'avatar-message');
// Connect to LiveKit for video
await connectToLiveKit();
} catch (error) {
console.error('Failed to start HeyGen session:', error);
updateAvatarStatus('Failed to start avatar session');
addMessage('System', `Failed to start avatar session: ${error.message}`, 'avatar-message');
}
}
async function sendToHeyGenAvatar(text) {
if (!heygenSessionId || !text) return;
try {
const response = await fetch(`http://localhost:8000/api/v1/heygen/session/${heygenSessionId}/task`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ text: text })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Text sent to HeyGen avatar:', data);
} catch (error) {
console.error('Failed to send text to HeyGen avatar:', error);
addMessage('System', `Failed to send to avatar: ${error.message}`, 'avatar-message');
}
}
async function closeHeyGenSession() {
if (!heygenSessionId) return;
try {
updateAvatarStatus('Closing avatar session...');
const response = await fetch(`http://localhost:8000/api/v1/heygen/session/${heygenSessionId}/close`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
console.log('HeyGen session closed');
heygenSessionId = null;
updateAvatarStatus('Avatar session closed');
// Reset video element
resetAvatarVideo();
} catch (error) {
console.error('Failed to close HeyGen session:', error);
updateAvatarStatus('Error closing avatar session');
}
}
// LiveKit connection for video
async function connectToLiveKit() {
if (!liveKitConnectionDetails) {
addMessage('System', 'No LiveKit connection details available', 'avatar-message');
return;
}
try {
updateAvatarStatus('Connecting to LiveKit...');
addMessage('System', 'Connecting to LiveKit for video stream...', 'avatar-message');
// Create LiveKit room
liveKitRoom = new LivekitClient.Room({
adaptiveStream: true,
dynacast: true,
audioCaptureDefaults: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
},
});
// Setup event handlers
liveKitRoom.on(LivekitClient.RoomEvent.TrackSubscribed, handleTrackSubscribed);
liveKitRoom.on(LivekitClient.RoomEvent.TrackUnsubscribed, handleTrackUnsubscribed);
liveKitRoom.on(LivekitClient.RoomEvent.Connected, () => {
console.log('LiveKit room connected successfully');
isLiveKitConnected = true;
updateAvatarStatus('Avatar Ready (LiveKit Connected)');
addMessage('System', '✅ LiveKit connected! Avatar video should appear shortly.', 'avatar-message');
});
liveKitRoom.on(LivekitClient.RoomEvent.Disconnected, () => {
console.log('LiveKit disconnected');
isLiveKitConnected = false;
updateAvatarStatus('LiveKit disconnected');
addMessage('System', '❌ LiveKit disconnected', 'avatar-message');
});
// Connect to LiveKit room
await liveKitRoom.connect(
liveKitConnectionDetails.livekit_url,
liveKitConnectionDetails.livekit_token
);
} catch (error) {
console.error('Failed to connect to LiveKit:', error);
updateAvatarStatus('LiveKit connection failed');
addMessage('System', `Failed to connect to LiveKit: ${error.message}`, 'avatar-message');
isLiveKitConnected = false;
}
}
// LiveKit event handlers
function handleTrackSubscribed(track, publication, participant) {
console.log(`Track subscribed: ${track.kind} from ${participant.identity}`);
addMessage('System', `📹 ${track.kind} track connected from avatar`, 'avatar-message');
if (track.kind === LivekitClient.Track.Kind.Video) {
const videoElement = document.getElementById('avatarVideo').querySelector('video') ||
document.createElement('video');
const placeholder = document.getElementById('avatarPlaceholder');
const container = document.getElementById('avatarVideo');
if (!videoElement.parentNode) {
videoElement.style.width = '100%';
videoElement.style.height = '100%';
videoElement.style.borderRadius = '10px';
videoElement.style.objectFit = 'cover';
videoElement.autoplay = true;
videoElement.playsInline = true;
videoElement.muted = false;
container.appendChild(videoElement);
}
track.attach(videoElement);
videoElement.style.display = 'block';
if (placeholder) placeholder.style.display = 'none';
videoElement.play().then(() => {
console.log('Avatar video stream connected and playing');
addMessage('System', '🎬 Avatar video is now playing!', 'avatar-message');
}).catch(err => {
console.error('Video play failed:', err);
addMessage('System', `Video play failed: ${err.message}`, 'avatar-message');
});
}
if (track.kind === LivekitClient.Track.Kind.Audio) {
console.log('Avatar audio track subscribed');
// Create dedicated audio element
const audioElement = document.createElement('audio');
audioElement.autoplay = true;
audioElement.controls = false;
audioElement.muted = false;
audioElement.volume = 1.0;
track.attach(audioElement);
audioElement.style.display = 'none';
document.body.appendChild(audioElement);
remoteAudioElements.set(track.sid, audioElement);
audioElement.play().then(() => {
console.log('Avatar audio track attached and playing');
addMessage('System', '🔊 Avatar audio connected!', 'avatar-message');
}).catch(err => {
console.error('Audio play failed:', err);
addMessage('System', `Audio play failed: ${err.message}`, 'avatar-message');
});
}
}
function handleTrackUnsubscribed(track, publication, participant) {
console.log(`Track unsubscribed: ${track.kind} from ${participant.identity}`);
if (track.kind === LivekitClient.Track.Kind.Video) {
const videoElement = document.getElementById('avatarVideo').querySelector('video');
const placeholder = document.getElementById('avatarPlaceholder');
if (videoElement) {
track.detach(videoElement);
videoElement.style.display = 'none';
}
if (placeholder) {
placeholder.style.display = 'flex';
}
}
if (track.kind === LivekitClient.Track.Kind.Audio) {
const audioElement = remoteAudioElements.get(track.sid);
if (audioElement) {
track.detach(audioElement);
audioElement.remove();
remoteAudioElements.delete(track.sid);
}
}
}
function resetAvatarVideo() {
const placeholder = document.getElementById('avatarPlaceholder');
const videoElement = document.getElementById('avatarVideo').querySelector('video');
if (videoElement) {
videoElement.remove();
}
if (placeholder) {
placeholder.style.display = 'flex';
placeholder.textContent = '🎭 Avatar will appear here when connected';
}
}
function updateAvatarStatus(status) {
const avatarStatus = document.getElementById('avatarStatus');
if (avatarStatus) {
avatarStatus.textContent = `Avatar Status: ${status}`;
}
}
// Auto-connect on page load
window.onload = () => {
addMessage('System', 'Welcome! Click "Connect to Avatar" to start testing.', 'avatar-message');
};
</script>
</body>
</html>