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
| class VideoChat { constructor() { this.localVideo = document.getElementById('localVideo'); this.remoteVideo = document.getElementById('remoteVideo'); this.startBtn = document.getElementById('startBtn'); this.callBtn = document.getElementById('callBtn'); this.joinBtn = document.getElementById('joinBtn'); this.leaveBtn = document.getElementById('leaveBtn'); this.roomIdInput = document.getElementById('roomId'); this.localStream = null; this.remoteStream = null; this.peerConnection = null; this.socket = null; this.roomId = null; this.configuration = { iceServers: [ { urls: [ 'stun:stun.l.google.com:19302', 'stun:stun1.l.google.com:19302' ] } ] }; this.bindEvents(); } bindEvents() { this.startBtn.addEventListener('click', () => this.startLocalVideo()); this.callBtn.addEventListener('click', () => this.callUser()); this.joinBtn.addEventListener('click', () => this.joinRoom()); this.leaveBtn.addEventListener('click', () => this.leaveRoom()); } async startLocalVideo() { try { const constraints = { video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 720 } }, audio: true }; this.localStream = await navigator.mediaDevices.getUserMedia(constraints); this.localVideo.srcObject = this.localStream; this.startBtn.disabled = true; this.callBtn.disabled = false; console.log('成功获取本地媒体流'); } catch (error) { console.error('获取本地媒体流失败:', error); let errorMessage = '无法访问摄像头或麦克风,请检查权限设置'; if (error.name === 'NotAllowedError') { errorMessage = '用户拒绝了摄像头或麦克风访问权限,请在浏览器设置中允许访问'; } else if (error.name === 'NotFoundError') { errorMessage = '未找到可用的摄像头或麦克风设备'; } else if (error.name === 'NotReadableError') { errorMessage = '摄像头或麦克风正被其他应用占用'; } else if (error.name === 'OverconstrainedError') { errorMessage = '摄像头不支持请求的分辨率或其他参数'; } else if (error.name === 'SecurityError') { if (location.protocol !== 'https:') { errorMessage = '当前页面不安全,无法访问摄像头或麦克风。请使用HTTPS访问'; } } alert(errorMessage); } } joinRoom() { const roomId = this.roomIdInput.value.trim(); if (!roomId) { alert('请输入房间号'); return; } this.roomId = roomId; console.log('正在加入房间:', roomId); const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsHost = window.location.hostname || 'localhost'; const wsPort = window.location.port ? window.location.port : (window.location.protocol === 'https:' ? '443' : '80'); const wsUrl = `${protocol}//${wsHost}:${wsPort}`; console.log('尝试连接WebSocket服务器:', wsUrl); this.socket = new WebSocket(wsUrl); this.socket.onopen = () => { console.log('[' + new Date().toISOString() + '] 成功连接到信令服务器'); console.log('发送加入房间请求:', { type: 'join', roomId: this.roomId }); this.sendMessage({ type: 'join', roomId: this.roomId }); }; this.socket.onmessage = (event) => { try { const data = JSON.parse(event.data); console.log('[' + new Date().toISOString() + '] 收到消息:', data); this.handleSignalingMessage(data); } catch (error) { console.error('[' + new Date().toISOString() + '] 解析消息失败:', error, '原始数据:', event.data); } }; this.socket.onclose = (event) => { console.log('[' + new Date().toISOString() + '] 与信令服务器断开连接:', event); if (event.wasClean) { console.log(`[${new Date().toISOString()}] 干净的关闭, 状态码: ${event.code}, 原因: ${event.reason}`); } else { console.warn(`[${new Date().toISOString()}] 意外关闭, 状态码: ${event.code}, 原因: ${event.reason}`); } }; this.socket.onerror = (error) => { console.error('[' + new Date().toISOString() + '] WebSocket连接错误:', error); alert('连接信令服务器失败,请检查网络连接\n错误: ' + error.message); if (this.socket) { this.socket.onopen = this.socket.onmessage = this.socket.onclose = this.socket.onerror = null; this.socket.close(); this.socket = null; } }; this.joinBtn.disabled = true; this.leaveBtn.disabled = false; } leaveRoom() { if (this.peerConnection) { this.peerConnection.close(); this.peerConnection = null; } if (this.socket) { this.socket.close(); this.socket = null; } if (this.localStream) { this.localStream.getTracks().forEach(track => track.stop()); this.localStream = null; } this.remoteVideo.srcObject = null; this.localVideo.srcObject = null; this.joinBtn.disabled = false; this.leaveBtn.disabled = true; this.startBtn.disabled = false; this.callBtn.disabled = true; } callUser() { console.log('[' + new Date().toISOString() + '] 发起呼叫'); if (!this.localStream) { console.error('[' + new Date().toISOString() + '] 无法发起呼叫:本地流未就绪'); alert('无法发起呼叫:本地视频流未就绪'); return; } this.createPeerConnection(); this.localStream.getTracks().forEach(track => { console.log('[' + new Date().toISOString() + '] 添加本地轨道:', track.kind, 'id:', track.id); this.peerConnection.addTrack(track, this.localStream); }); this.peerConnection.createOffer() .then(offer => { console.log('[' + new Date().toISOString() + '] 创建offer成功:', offer); return this.peerConnection.setLocalDescription(offer); }) .then(() => { console.log('[' + new Date().toISOString() + '] 设置本地描述成功:', this.peerConnection.localDescription); this.sendMessage({ type: 'offer', roomId: this.roomId, offer: this.peerConnection.localDescription }); }) .catch(error => { console.error('[' + new Date().toISOString() + '] 创建offer失败:', error); alert('建立连接失败,请重试\n错误: ' + error.message); }); } createPeerConnection() { console.log('[' + new Date().toISOString() + '] 创建RTCPeerConnection,配置:', this.configuration); this.peerConnection = new RTCPeerConnection(this.configuration); this.peerConnection.onicecandidate = (event) => { if (event.candidate) { console.log('[' + new Date().toISOString() + '] 发现ICE候选:', event.candidate); this.sendMessage({ type: 'candidate', roomId: this.roomId, candidate: event.candidate }); } else { console.log('[' + new Date().toISOString() + '] ICE收集完成'); } }; this.peerConnection.ontrack = (event) => { console.log('[' + new Date().toISOString() + '] 收到远程轨道:', event.track.kind, 'id:', event.track.id); console.log('[' + new Date().toISOString() + '] 流信息:', event.streams[0]); this.remoteVideo.srcObject = event.streams[0]; }; this.peerConnection.onconnectionstatechange = () => { const state = this.peerConnection.connectionState; console.log('[' + new Date().toISOString() + '] 连接状态变化:', state); switch (state) { case 'new': console.log('[' + new Date().toISOString() + '] 连接新建'); break; case 'connecting': console.log('[' + new Date().toISOString() + '] 正在连接'); break; case 'connected': console.log('[' + new Date().toISOString() + '] 连接成功建立'); alert('连接已建立,可以开始视频通话'); break; case 'disconnected': console.log('[' + new Date().toISOString() + '] 连接断开'); break; case 'failed': console.error('[' + new Date().toISOString() + '] 连接失败'); alert('连接失败,请检查网络或重试'); break; case 'closed': console.log('[' + new Date().toISOString() + '] 连接已关闭'); break; } }; this.peerConnection.oniceconnectionstatechange = () => { const state = this.peerConnection.iceConnectionState; console.log('[' + new Date().toISOString() + '] ICE连接状态变化:', state); switch (state) { case 'new': console.log('[' + new Date().toISOString() + '] ICE连接新建'); break; case 'checking': console.log('[' + new Date().toISOString() + '] ICE连接检查中'); break; case 'connected': console.log('[' + new Date().toISOString() + '] ICE连接已连接'); break; case 'completed': console.log('[' + new Date().toISOString() + '] ICE连接完成'); break; case 'disconnected': console.log('[' + new Date().toISOString() + '] ICE连接断开'); break; case 'failed': console.error('[' + new Date().toISOString() + '] ICE连接失败'); break; case 'closed': console.log('[' + new Date().toISOString() + '] ICE连接已关闭'); break; } }; } handleSignalingMessage(message) { console.log('处理信令消息:', message); switch (message.type) { case 'offer': this.handleOffer(message.offer); break; case 'answer': this.handleAnswer(message.answer); break; case 'candidate': this.handleCandidate(message.candidate); break; case 'ready': console.log('收到ready消息,可以发起呼叫'); this.callBtn.disabled = false; if (this.localStream) { console.log('本地流已准备好,自动发起呼叫'); setTimeout(() => { this.callUser(); }, 1000); } break; case 'full': alert('房间已满'); this.leaveRoom(); break; case 'leave': console.log('对方已离开房间'); alert('对方已离开房间'); this.leaveRoom(); break; } } async handleOffer(offer) { console.log('收到offer:', offer); if (!this.peerConnection) { this.createPeerConnection(); if (this.localStream) { this.localStream.getTracks().forEach(track => { console.log('添加本地轨道到连接:', track.kind); this.peerConnection.addTrack(track, this.localStream); }); } else { console.error('本地流未准备好'); } } try { await this.peerConnection.setRemoteDescription(offer); console.log('已设置远程offer描述'); const answer = await this.peerConnection.createAnswer(); console.log('创建answer成功:', answer); await this.peerConnection.setLocalDescription(answer); console.log('已设置本地answer描述'); this.sendMessage({ type: 'answer', roomId: this.roomId, answer: this.peerConnection.localDescription }); } catch (error) { console.error('处理offer时出错:', error); } } async handleAnswer(answer) { console.log('收到answer:', answer); try { await this.peerConnection.setRemoteDescription(answer); console.log('已设置远程answer描述'); } catch (error) { console.error('处理answer时出错:', error); } } async handleCandidate(candidate) { console.log('收到ICE候选:', candidate); if (this.peerConnection) { try { await this.peerConnection.addIceCandidate(candidate); console.log('已添加ICE候选'); } catch (error) { console.error('添加ICE候选时出错:', error); } } else { console.warn('收到ICE候选但连接未建立'); } } sendMessage(message) { if (!message) { console.warn('[' + new Date().toISOString() + '] 尝试发送空消息'); return; } if (this.socket && this.socket.readyState === WebSocket.OPEN) { const messageStr = JSON.stringify(message); console.log('[' + new Date().toISOString() + '] 发送消息:', message); this.socket.send(messageStr); } else { console.warn('[' + new Date().toISOString() + '] 无法发送消息,WebSocket未打开,状态:', this.socket ? this.socket.readyState : '无socket'); } } }
document.addEventListener('DOMContentLoaded', () => { new VideoChat(); });
|