File size: 6,792 Bytes
2cf3f60 3a86964 2cf3f60 bc2bce0 2cf3f60 |
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 |
<!DOCTYPE html>
<html>
<head>
<title>Voice Agent</title>
<style>
.call-button {
padding: 20px 40px;
font-size: 24px;
border-radius: 50px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
transition: all 0.3s;
}
.call-button.active {
background-color: #f44336;
}
.status {
margin-top: 20px;
font-size: 18px;
}
.volume-meter {
width: 300px;
height: 20px;
background-color: #ddd;
margin: 20px auto;
border-radius: 10px;
overflow: hidden;
}
.volume-level {
height: 100%;
width: 0%;
background-color: #4CAF50;
transition: width 0.1s;
}
</style>
</head>
<body>
<div style="text-align: center; padding: 50px;">
<button id="callButton" class="call-button">Start Call</button>
<div class="volume-meter">
<div id="volumeLevel" class="volume-level"></div>
</div>
<div id="status" class="status"></div>
</div>
<script>
let ws, mediaRecorder, audioChunks = [];
let isListening = false;
let isPlayingResponse = false;
let audioContext, analyser, dataArray;
const silenceThreshold = -40;
const silenceTime = 2.0;
let lastAudioLevel = Date.now();
const callButton = document.getElementById('callButton');
const statusDiv = document.getElementById('status');
const volumeLevel = document.getElementById('volumeLevel');
async function startCall() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
setupAudioAnalyser(stream);
ws = new WebSocket(`wss://puzan789-arkos.hf.space/ws/voicechat`);
ws.onopen = () => {
statusDiv.textContent = 'Connected - Ready to listen';
callButton.classList.add('active');
callButton.textContent = 'End Call';
startListening(stream);
};
ws.onmessage = async (event) => {
const data = JSON.parse(event.data);
stopListening(); // Stop listening while processing response
if (data.audio) {
statusDiv.innerHTML = `<b>You said:</b> ${data.transcript}<br><b>AI is responding...</b>`;
// Play audio response
const binaryString = atob(data.audio);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const audioBlob = new Blob([bytes], { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.onended = () => {
ws.send("audio_complete");
statusDiv.innerHTML = `<b>You said:</b> ${data.transcript}<br><b>AI responded:</b> ${data.response}<br><b>Ready for next input</b>`;
startListening(stream); // Resume listening
};
audio.play();
}
};
ws.onclose = () => stopCall();
} catch (error) {
console.error('Error:', error);
statusDiv.textContent = 'Error: ' + error.message;
}
}
function setupAudioAnalyser(stream) {
audioContext = new AudioContext();
analyser = audioContext.createAnalyser();
const source = audioContext.createMediaStreamSource(stream);
source.connect(analyser);
analyser.fftSize = 2048;
dataArray = new Float32Array(analyser.frequencyBinCount);
}
function getAudioLevel() {
analyser.getFloatTimeDomainData(dataArray);
let sum = 0;
for (let i = 0; i < dataArray.length; i++) {
sum += dataArray[i] * dataArray[i];
}
const rms = Math.sqrt(sum / dataArray.length);
const db = 20 * Math.log10(rms);
return db;
}
function updateVolumeMeter() {
if (analyser && isListening) {
const db = getAudioLevel();
const normalizedDb = Math.max(0, Math.min(100, (db + 60) * 2));
volumeLevel.style.width = normalizedDb + '%';
if (db > silenceThreshold) {
lastAudioLevel = Date.now();
} else if (Date.now() - lastAudioLevel > silenceTime * 1000) {
sendAudio();
lastAudioLevel = Date.now();
}
}
requestAnimationFrame(updateVolumeMeter);
}
function startListening(stream) {
isListening = true;
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = async (event) => {
if (event.data.size > 0) {
audioChunks.push(event.data);
}
};
mediaRecorder.start(250);
updateVolumeMeter();
}
function stopListening() {
isListening = false;
if (mediaRecorder && mediaRecorder.state === 'recording') {
mediaRecorder.stop();
}
audioChunks = [];
volumeLevel.style.width = '0%';
}
async function sendAudio() {
if (audioChunks.length > 0 && ws.readyState === WebSocket.OPEN) {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
ws.send(await audioBlob.arrayBuffer());
audioChunks = [];
stopListening();
}
}
function stopCall() {
if (ws) ws.close();
stopListening();
if (audioContext) audioContext.close();
callButton.classList.remove('active');
callButton.textContent = 'Start Call';
}
callButton.addEventListener('click', () => {
if (!ws || ws.readyState === WebSocket.CLOSED) {
startCall();
} else {
stopCall();
}
});
</script>
</body>
</html> |