File size: 11,270 Bytes
56d02e9 |
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 |
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<style>
#videoElement {
width: 640px;
height: 480px;
border-radius: 20px;
}
#canvasElement {
display: none;
width: 640px;
height: 480px;
}
.demo-content {
padding: 20px;
display: flex;
flex-direction: column;
align-items: center;
}
.button-group {
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header">
<div class="mdl-layout__header-row">
<!-- Title -->
<span class="mdl-layout-title">Gemini Live Demo</span>
</div>
</header>
<main class="mdl-layout__content">
<div class="page-content">
<div class="demo-content">
<!-- Voice Control Buttons -->
<div class="button-group">
<button id="startButton"
class="mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab mdl-button--colored">
<i class="material-icons">mic</i>
</button>
<button id="stopButton"
class="mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab">
<i class="material-icons">mic_off</i>
</button>
</div>
<!-- Video Element -->
<video id="videoElement" autoplay style="width: 640px; height: 480px;"></video>
<!-- Hidden Canvas -->
<canvas id="canvasElement" style="width: 640px; height: 480px;"></canvas>
<!-- Text Output -->
<div id="chatLog"></div>
</div>
</div>
</main>
</div>
<script defer>
const URL = "ws://localhost:9083";
const video = document.getElementById("videoElement");
const canvas = document.getElementById("canvasElement");
let context;
// Initialize context here
window.addEventListener("load", () => {
context = canvas.getContext("2d");
setInterval(captureImage, 3000);
});
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
let stream = null;
let currentFrameB64;
let webSocket = null;
let audioContext = null;
let mediaRecorder = null;
let processor = null;
let pcmData = [];
let interval = null;
let initialized = false;
let audioInputContext;
let workletNode;
// Function to start screen capture
async function startScreenShare() {
try {
stream = await navigator.mediaDevices.getDisplayMedia({
video: {
width: { max: 640 },
height: { max: 480 },
},
});
video.srcObject = stream;
await new Promise(resolve => {
video.onloadedmetadata = () => {
console.log("video loaded metadata");
resolve();
}
});
} catch (err) {
console.error("Error accessing the screen: ", err);
}
}
// Function to capture an image from the shared screen
function captureImage() {
if (stream && video.videoWidth > 0 && video.videoHeight > 0 && context) {
canvas.width = 640;
canvas.height = 480;
context.drawImage(video, 0, 0, canvas.width, canvas.height);
const imageData = canvas.toDataURL("image/jpeg").split(",")[1].trim();
currentFrameB64 = imageData;
}
else {
console.log("no stream or video metadata not loaded");
}
}
window.addEventListener("load", async () => {
await startScreenShare();
//setInterval(captureImage, 3000);
// Initialize audio context right away
await initializeAudioContext();
connect();
});
function connect() {
console.log("connecting: ", URL);
webSocket = new WebSocket(URL);
webSocket.onclose = (event) => {
console.log("websocket closed: ", event);
alert("Connection closed");
};
webSocket.onerror = (event) => {
console.log("websocket error: ", event);
};
webSocket.onopen = (event) => {
console.log("websocket open: ", event);
sendInitialSetupMessage();
};
webSocket.onmessage = receiveMessage;
}
function sendInitialSetupMessage() {
console.log("sending setup message");
setup_client_message = {
setup: {
generation_config: { response_modalities: ["AUDIO"] },
},
};
webSocket.send(JSON.stringify(setup_client_message));
}
function sendVoiceMessage(b64PCM) {
if (webSocket == null) {
console.log("websocket not initialized");
return;
}
payload = {
realtime_input: {
media_chunks: [{
mime_type: "audio/pcm",
data: b64PCM,
},
{
mime_type: "image/jpeg",
data: currentFrameB64,
},
],
},
};
webSocket.send(JSON.stringify(payload));
console.log("sent: ", payload);
}
function receiveMessage(event) {
const messageData = JSON.parse(event.data);
const response = new Response(messageData);
if (response.text) {
displayMessage("GEMINI: " + response.text);
}
if (response.audioData) {
injestAudioChuckToPlay(response.audioData);
}
}
async function initializeAudioContext() {
if (initialized) return;
audioInputContext = new (window.AudioContext ||
window.webkitAudioContext)({
sampleRate: 24000
});
await audioInputContext.audioWorklet.addModule("pcm-processor.js");
workletNode = new AudioWorkletNode(audioInputContext, "pcm-processor");
workletNode.connect(audioInputContext.destination);
initialized = true;
}
function base64ToArrayBuffer(base64) {
const binaryString = window.atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
function convertPCM16LEToFloat32(pcmData) {
const inputArray = new Int16Array(pcmData);
const float32Array = new Float32Array(inputArray.length);
for (let i = 0; i < inputArray.length; i++) {
float32Array[i] = inputArray[i] / 32768;
}
return float32Array;
}
async function injestAudioChuckToPlay(base64AudioChunk) {
try {
if (audioInputContext.state === "suspended") {
await audioInputContext.resume();
}
const arrayBuffer = base64ToArrayBuffer(base64AudioChunk);
const float32Data = convertPCM16LEToFloat32(arrayBuffer);
workletNode.port.postMessage(float32Data);
} catch (error) {
console.error("Error processing audio chunk:", error);
}
}
function recordChunk() {
const buffer = new ArrayBuffer(pcmData.length * 2);
const view = new DataView(buffer);
pcmData.forEach((value, index) => {
view.setInt16(index * 2, value, true);
});
const base64 = btoa(
String.fromCharCode.apply(null, new Uint8Array(buffer))
);
sendVoiceMessage(base64);
pcmData = [];
}
async function startAudioInput() {
audioContext = new AudioContext({
sampleRate: 16000,
});
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
channelCount: 1,
sampleRate: 16000,
},
});
const source = audioContext.createMediaStreamSource(stream);
processor = audioContext.createScriptProcessor(4096, 1, 1);
processor.onaudioprocess = (e) => {
const inputData = e.inputBuffer.getChannelData(0);
const pcm16 = new Int16Array(inputData.length);
for (let i = 0; i < inputData.length; i++) {
pcm16[i] = inputData[i] * 0x7fff;
}
pcmData.push(...pcm16);
};
source.connect(processor);
processor.connect(audioContext.destination);
interval = setInterval(recordChunk, 3000);
}
function stopAudioInput() {
if (processor) {
processor.disconnect();
}
if (audioContext) {
audioContext.close();
}
clearInterval(interval);
}
function displayMessage(message) {
console.log(message);
addParagraphToDiv("chatLog", message);
}
function addParagraphToDiv(divId, text) {
const newParagraph = document.createElement("p");
newParagraph.textContent = text;
const div = document.getElementById(divId);
div.appendChild(newParagraph);
}
startButton.addEventListener('click', startAudioInput);
stopButton.addEventListener('click', stopAudioInput);
class Response {
constructor(data) {
this.text = null;
this.audioData = null;
this.endOfTurn = null;
if (data.text) {
this.text = data.text
}
if (data.audio) {
this.audioData = data.audio;
}
}
}
</script>
</body>
</html> |