server-recording.js 12.2 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
// AIfeng/2025-07-08 15:59:04
// 服务端录音前端模块 - WebSocket通信和UI控制
// 核心功能:服务端录音控制、识别结果接收、状态同步

class ServerRecordingClient {
    constructor(options = {}) {
        this.options = {
            wsUrl: options.wsUrl || `ws://${window.location.host}/ws/server-recording`,
            sessionId: options.sessionId || `session_${Date.now()}`,
            autoReconnect: options.autoReconnect !== false,
            reconnectInterval: options.reconnectInterval || 3000,
            maxReconnectAttempts: options.maxReconnectAttempts || 5,
            ...options
        };
        
        this.ws = null;
        this.isConnected = false;
        this.isRecording = false;
        this.reconnectAttempts = 0;
        this.reconnectTimer = null;
        
        // 事件回调
        this.onConnected = null;
        this.onDisconnected = null;
        this.onRecordingStarted = null;
        this.onRecordingStopped = null;
        this.onPartialResult = null;
        this.onFinalResult = null;
        this.onSessionComplete = null;
        this.onStatusUpdate = null;
        this.onError = null;
        
        console.log('ServerRecordingClient初始化完成', this.options);
    }
    
    /**
     * 连接到服务端录音WebSocket
     */
    async connect() {
        try {
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                console.log('WebSocket已连接,跳过重复连接');
                return true;
            }
            
            console.log('正在连接服务端录音WebSocket:', this.options.wsUrl);
            
            this.ws = new WebSocket(this.options.wsUrl);
            
            return new Promise((resolve, reject) => {
                const timeout = setTimeout(() => {
                    reject(new Error('连接超时'));
                }, 10000);
                
                this.ws.onopen = () => {
                    clearTimeout(timeout);
                    console.log('WebSocket连接已建立');
                    this.isConnected = true;
                    this.reconnectAttempts = 0;
                    
                    // 发送连接请求
                    this.sendMessage({
                        type: 'connect',
                        session_id: this.options.sessionId
                    });
                    
                    resolve(true);
                };
                
                this.ws.onmessage = (event) => {
                    this.handleMessage(event.data);
                };
                
                this.ws.onclose = (event) => {
                    clearTimeout(timeout);
                    console.log('WebSocket连接关闭:', event.code, event.reason);
                    this.isConnected = false;
                    this.isRecording = false;
                    
                    if (this.onDisconnected) {
                        this.onDisconnected(event);
                    }
                    
                    // 自动重连
                    if (this.options.autoReconnect && this.reconnectAttempts < this.options.maxReconnectAttempts) {
                        this.scheduleReconnect();
                    }
                };
                
                this.ws.onerror = (error) => {
                    clearTimeout(timeout);
                    console.error('WebSocket错误:', error);
                    
                    if (this.onError) {
                        this.onError(error);
                    }
                    
                    reject(error);
                };
            });
            
        } catch (error) {
            console.error('连接失败:', error);
            if (this.onError) {
                this.onError(error);
            }
            throw error;
        }
    }
    
    /**
     * 断开连接
     */
    disconnect() {
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
            this.reconnectTimer = null;
        }
        
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
        
        this.isConnected = false;
        this.isRecording = false;
        console.log('WebSocket连接已断开');
    }
    
    /**
     * 开始服务端录音
     */
    async startRecording(config = {}) {
        try {
            if (!this.isConnected) {
                throw new Error('WebSocket未连接');
            }
            
            if (this.isRecording) {
                console.log('录音已在进行中');
                return false;
            }
            
            console.log('开始服务端录音', config);
            
            this.sendMessage({
                type: 'start_recording',
                session_id: this.options.sessionId,
                config: config
            });
            
            return true;
            
        } catch (error) {
            console.error('开始录音失败:', error);
            if (this.onError) {
                this.onError(error);
            }
            throw error;
        }
    }
    
    /**
     * 停止服务端录音
     */
    async stopRecording() {
        try {
            if (!this.isConnected) {
                throw new Error('WebSocket未连接');
            }
            
            if (!this.isRecording) {
                console.log('没有正在进行的录音');
                return false;
            }
            
            console.log('停止服务端录音');
            
            this.sendMessage({
                type: 'stop_recording',
                session_id: this.options.sessionId
            });
            
            return true;
            
        } catch (error) {
            console.error('停止录音失败:', error);
            if (this.onError) {
                this.onError(error);
            }
            throw error;
        }
    }
    
    /**
     * 获取录音状态
     */
    async getStatus() {
        try {
            if (!this.isConnected) {
                throw new Error('WebSocket未连接');
            }
            
            this.sendMessage({
                type: 'get_status',
                session_id: this.options.sessionId
            });
            
        } catch (error) {
            console.error('获取状态失败:', error);
            if (this.onError) {
                this.onError(error);
            }
            throw error;
        }
    }
    
    /**
     * 发送消息到服务端
     */
    sendMessage(message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(message));
        } else {
            console.error('WebSocket未连接,无法发送消息:', message);
        }
    }
    
    /**
     * 处理服务端消息
     */
    handleMessage(data) {
        try {
            const message = JSON.parse(data);
            console.log('收到服务端消息:', message);
            
            switch (message.type) {
                case 'connected':
                    this.handleConnected(message);
                    break;
                    
                case 'recording_started':
                    this.handleRecordingStarted(message);
                    break;
                    
                case 'recording_stopped':
                    this.handleRecordingStopped(message);
                    break;
                    
                case 'asr_partial_result':
                    this.handlePartialResult(message);
                    break;
                    
                case 'asr_final_result':
                    this.handleFinalResult(message);
                    break;
                    
                case 'asr_session_complete':
                    this.handleSessionComplete(message);
                    break;
                    
                case 'status_update':
                    this.handleStatusUpdate(message);
                    break;
                    
                case 'status':
                    this.handleStatus(message);
                    break;
                    
                case 'error':
                    this.handleError(message);
                    break;
                    
                case 'warning':
                    this.handleWarning(message);
                    break;
                    
                case 'pong':
                    // 心跳响应
                    break;
                    
                default:
                    console.log('未知消息类型:', message.type);
            }
            
        } catch (error) {
            console.error('处理消息失败:', error, data);
        }
    }
    
    /**
     * 处理连接成功
     */
    handleConnected(message) {
        console.log('服务端录音连接成功:', message);
        if (this.onConnected) {
            this.onConnected(message);
        }
    }
    
    /**
     * 处理录音开始
     */
    handleRecordingStarted(message) {
        console.log('服务端录音已开始:', message);
        this.isRecording = true;
        if (this.onRecordingStarted) {
            this.onRecordingStarted(message);
        }
    }
    
    /**
     * 处理录音停止
     */
    handleRecordingStopped(message) {
        console.log('服务端录音已停止:', message);
        this.isRecording = false;
        if (this.onRecordingStopped) {
            this.onRecordingStopped(message);
        }
    }
    
    /**
     * 处理部分识别结果
     */
    handlePartialResult(message) {
        console.log('部分识别结果:', message.data);
        if (this.onPartialResult) {
            this.onPartialResult(message.data, message);
        }
    }
    
    /**
     * 处理最终识别结果
     */
    handleFinalResult(message) {
        console.log('最终识别结果:', message.data);
        if (this.onFinalResult) {
            this.onFinalResult(message.data, message);
        }
    }
    
    /**
     * 处理会话完成
     */
    handleSessionComplete(message) {
        console.log('识别会话完成:', message.data);
        if (this.onSessionComplete) {
            this.onSessionComplete(message.data, message);
        }
    }
    
    /**
     * 处理状态更新
     */
    handleStatusUpdate(message) {
        console.log('状态更新:', message.data);
        if (this.onStatusUpdate) {
            this.onStatusUpdate(message.data, message);
        }
    }
    
    /**
     * 处理状态查询结果
     */
    handleStatus(message) {
        console.log('当前状态:', message.data);
        this.isRecording = message.data.recording || false;
        if (this.onStatusUpdate) {
            this.onStatusUpdate(message.data, message);
        }
    }
    
    /**
     * 处理错误
     */
    handleError(message) {
        console.error('服务端错误:', message.message);
        if (this.onError) {
            this.onError(new Error(message.message), message);
        }
    }
    
    /**
     * 处理警告
     */
    handleWarning(message) {
        console.warn('服务端警告:', message.message);
    }
    
    /**
     * 安排重连
     */
    scheduleReconnect() {
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
        }
        
        this.reconnectAttempts++;
        console.log(`安排重连 (${this.reconnectAttempts}/${this.options.maxReconnectAttempts})`);
        
        this.reconnectTimer = setTimeout(() => {
            this.connect().catch(error => {
                console.error('重连失败:', error);
            });
        }, this.options.reconnectInterval);
    }
    
    /**
     * 发送心跳
     */
    ping() {
        this.sendMessage({ type: 'ping' });
    }
    
    /**
     * 获取连接状态
     */
    getConnectionState() {
        return {
            isConnected: this.isConnected,
            isRecording: this.isRecording,
            sessionId: this.options.sessionId,
            reconnectAttempts: this.reconnectAttempts
        };
    }
}

// 导出类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ServerRecordingClient;
} else if (typeof window !== 'undefined') {
    window.ServerRecordingClient = ServerRecordingClient;
}