-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
76 lines (67 loc) · 2.31 KB
/
script.js
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
import { Conversation } from '@11labs/client';
// DOM Elements
const micButton = document.getElementById('micButton');
const termsModal = document.getElementById('termsModal');
const agreeButton = document.getElementById('agreeButton');
const connectionStatus = document.getElementById('connectionStatus');
const agentStatus = document.getElementById('agentStatus');
let conversation = null;
let isRunning = false;
// Terms and Conditions Logic
agreeButton.addEventListener('click', () => {
// Hide the modal
termsModal.style.display = 'none';
// Enable the "Start" button
micButton.disabled = false;
});
// Bot Logic
async function startConversation() {
try {
await navigator.mediaDevices.getUserMedia({ audio: true });
conversation = await Conversation.startSession({
agentId: 'PsNR98dYRFTCCDJvkRPS', // Replace with your Agent ID
onConnect: () => {
updateUI('connected', 'listening');
},
onDisconnect: () => {
updateUI('disconnected', 'idle');
},
onError: (error) => {
console.error('Error:', error);
updateUI('disconnected', 'error');
},
onModeChange: (mode) => {
if (mode.mode === 'speaking') {
updateUI('connected', 'speaking');
} else if (mode.mode === 'listening') {
updateUI('connected', 'listening');
}
},
});
} catch (error) {
console.error('Failed to start conversation:', error);
updateUI('disconnected', 'error');
}
}
async function stopConversation() {
if (conversation) {
await conversation.endSession();
conversation = null;
updateUI('disconnected', 'idle');
}
}
function updateUI(connectionState, agentState) {
connectionStatus.textContent =
connectionState === 'connected' ? 'Connected' : 'Disconnected';
agentStatus.textContent = agentState;
micButton.querySelector('h5').textContent =
connectionState === 'connected' ? 'Stop' : 'Start';
isRunning = connectionState === 'connected';
}
micButton.addEventListener('click', async () => {
if (!isRunning) {
await startConversation();
} else {
await stopConversation();
}
});