@zeewain/3d-avatar-sdk 1.2.2 → 1.2.4-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13253,6 +13253,7 @@
13253
13253
  /**
13254
13254
  * 获取指定环境的配置
13255
13255
  * @param env - 环境类型,默认为'dev'
13256
+ * @param withApiModule - 是否包含API模块路径
13256
13257
  * @returns 返回对应环境的配置对象
13257
13258
  * @example
13258
13259
  * ```typescript
@@ -13260,17 +13261,17 @@
13260
13261
  * console.log(config.apiBaseUrl); // https://aiip.zeewain.com/api/dh-talker
13261
13262
  * ```
13262
13263
  */
13263
- function getEnvConfig(env, withModule) {
13264
+ function getEnvConfig(env, withApiModule) {
13264
13265
  if (env === void 0) {
13265
13266
  env = 'dev';
13266
13267
  }
13267
- if (withModule === void 0) {
13268
- withModule = true;
13268
+ if (withApiModule === void 0) {
13269
+ withApiModule = true;
13269
13270
  }
13270
13271
  var baseUrl = ENV_MAP[env];
13271
13272
  if (baseUrl) {
13272
13273
  return {
13273
- apiBaseUrl: "".concat(baseUrl.apiBaseUrl).concat(withModule ? '/api' : '')
13274
+ apiBaseUrl: "".concat(baseUrl.apiBaseUrl).concat(withApiModule ? '/api' : '')
13274
13275
  };
13275
13276
  }
13276
13277
  return null;
@@ -13343,20 +13344,20 @@
13343
13344
  };
13344
13345
  /**
13345
13346
  * 获取API基础URL
13346
- * @param withModule 是否包含模块路径
13347
+ * @param withApiModule 是否包含模块路径
13347
13348
  * @returns string API基础URL
13348
13349
  * @description 根据当前环境配置获取API基础URL
13349
13350
  */
13350
- ConfigManager.prototype.getApiBaseUrl = function (withModule) {
13351
+ ConfigManager.prototype.getApiBaseUrl = function (withApiModule) {
13351
13352
  var _a, _b, _c, _d;
13352
- if (withModule === void 0) {
13353
- withModule = true;
13353
+ if (withApiModule === void 0) {
13354
+ withApiModule = true;
13354
13355
  }
13355
13356
  if (((_a = this.config) === null || _a === void 0 ? void 0 : _a.env) === 'custom' && ((_b = this.config) === null || _b === void 0 ? void 0 : _b.apiUrl)) {
13356
13357
  // 如果环境为自定义,则直接返回配置的API,无需添加模块路径
13357
- return this.config.apiUrl;
13358
+ return "".concat(this.config.apiUrl).concat(withApiModule ? '/api' : '');
13358
13359
  }
13359
- return ((_d = getEnvConfig(((_c = this.config) === null || _c === void 0 ? void 0 : _c.env) || 'prod', withModule)) === null || _d === void 0 ? void 0 : _d.apiBaseUrl) || '';
13360
+ return ((_d = getEnvConfig(((_c = this.config) === null || _c === void 0 ? void 0 : _c.env) || 'prod', withApiModule)) === null || _d === void 0 ? void 0 : _d.apiBaseUrl) || '';
13360
13361
  };
13361
13362
  /**
13362
13363
  * 获取自定义API URL
@@ -13768,6 +13769,20 @@
13768
13769
  * @fileoverview 流式播报服务重构实现模块
13769
13770
  * @description 提供流式播报服务的重构实现,继承Unity基础服务,支持文本转语音和自定义音频播报
13770
13771
  */
13772
+ /**
13773
+ * 播报任务状态枚举
13774
+ */
13775
+ var BroadcastTaskStatus;
13776
+ (function (BroadcastTaskStatus) {
13777
+ /** 请求中 */
13778
+ BroadcastTaskStatus["REQUESTING"] = "requesting";
13779
+ /** 已完成 */
13780
+ BroadcastTaskStatus["COMPLETED"] = "completed";
13781
+ /** 失败 */
13782
+ BroadcastTaskStatus["FAILED"] = "failed";
13783
+ /** 已取消 */
13784
+ BroadcastTaskStatus["CANCELLED"] = "cancelled";
13785
+ })(BroadcastTaskStatus || (BroadcastTaskStatus = {}));
13771
13786
  /**
13772
13787
  * 流式播报服务重构类
13773
13788
  * @class BroadcastServiceRefactored
@@ -13798,12 +13813,20 @@
13798
13813
  var _this = _super.call(this, config) || this;
13799
13814
  /** 事件回调函数集合 */
13800
13815
  _this.callbacks = {};
13801
- /** 请求控制器,用于取消请求 */
13802
- _this.activeController = null;
13816
+ /** 播报任务队列 */
13817
+ _this.taskQueue = [];
13818
+ /** 任务序号计数器 */
13819
+ _this.taskSequence = 0;
13820
+ /** 当前发送任务的序号 */
13821
+ _this.currentSendingSequence = 0;
13803
13822
  /** 是否正在生成音频 */
13804
13823
  _this.isGeneratingAudio = false;
13805
13824
  /** 是否已经收到音频 */
13806
13825
  _this.hasReceivedAudio = false;
13826
+ /** 队列处理定时器 */
13827
+ _this.queueProcessTimer = null;
13828
+ /** 主请求控制器(兼容性保留) */
13829
+ _this.activeController = null;
13807
13830
  _this.callbacks = config.callbacks || {};
13808
13831
  _this.logger.info('Broadcast service initialized', {
13809
13832
  config: config
@@ -13854,8 +13877,9 @@
13854
13877
  /**
13855
13878
  * 开始播报
13856
13879
  * @param params - 播报参数
13880
+ * @param isAppend - 是否追加播报
13857
13881
  * @returns Promise<void> 播报操作的Promise
13858
- * @description 开始流式播报,支持文本转语音和自定义音频播报
13882
+ * @description 开始流式播报,支持文本转语音和自定义音频播报。使用队列机制确保音频按序播报
13859
13883
  * @throws {SDKError} 当参数验证失败或播报失败时抛出错误
13860
13884
  * @example
13861
13885
  * ```typescript
@@ -13869,49 +13893,40 @@
13869
13893
  * isSubtitle: true
13870
13894
  * });
13871
13895
  *
13872
- * // 自定义音频播报
13896
+ * // 追加播报(会进入队列按序播报)
13873
13897
  * await broadcastService.startBroadcast({
13874
- * type: BroadcastType.AUDIO,
13898
+ * type: BroadcastType.TEXT,
13875
13899
  * humanCode: 'human001',
13876
- * audioUrl: 'https://example.com/audio.mp3',
13900
+ * text: '这是第二段内容',
13901
+ * voiceCode: 'voice001',
13877
13902
  * volume: 0.8,
13878
- * isSubtitle: false
13879
- * });
13903
+ * isSubtitle: true
13904
+ * }, true);
13880
13905
  * ```
13881
13906
  */
13882
- BroadcastService.prototype.startBroadcast = function (params) {
13907
+ BroadcastService.prototype.startBroadcast = function (params, isAppend) {
13883
13908
  return __awaiter(this, void 0, void 0, function () {
13884
- var apiUrl, requestBody, error_1;
13885
- var _this = this;
13909
+ var task;
13886
13910
  var _a, _b;
13887
13911
  return __generator(this, function (_c) {
13888
13912
  switch (_c.label) {
13889
13913
  case 0:
13890
13914
  this.logger.info("Starting broadcast: ".concat(params.type), {
13891
- humanCode: params.humanCode
13915
+ humanCode: params.humanCode,
13916
+ isAppend: isAppend,
13917
+ queueLength: this.taskQueue.length
13892
13918
  });
13893
13919
  // 验证参数
13894
13920
  this.validateBroadcastParams(params);
13895
- // 先停止当前播报
13921
+ if (!!isAppend) return [3 /*break*/, 2];
13922
+ // 先停止当前播报并清空队列
13896
13923
  return [4 /*yield*/, this.stopBroadcast()];
13897
13924
  case 1:
13898
- // 先停止当前播报
13925
+ // 先停止当前播报并清空队列
13899
13926
  _c.sent();
13900
- // 创建新的请求控制器
13901
- this.activeController = new AbortController();
13902
- // 监听中断信号
13903
- this.activeController.signal.addEventListener('abort', function () {
13904
- var _a, _b;
13905
- console.warn('abort');
13906
- // 如果正在生成音频,触发中断回调
13907
- if (_this.isGeneratingAudio) {
13908
- (_b = (_a = _this.callbacks).onAbort) === null || _b === void 0 ? void 0 : _b.call(_a);
13909
- }
13910
- // 重置状态
13911
- _this.isGeneratingAudio = false;
13912
- _this.hasReceivedAudio = false;
13913
- _this.activeController = null;
13914
- });
13927
+ // 重置序号计数器
13928
+ this.taskSequence = 0;
13929
+ this.currentSendingSequence = 0;
13915
13930
  // 通知Unity开始新任务(清空队列)
13916
13931
  this.sendMessage('StartBroadcast', {
13917
13932
  callbackFun: this.uniqueCallbackName,
@@ -13919,100 +13934,19 @@
13919
13934
  motionList: params.motionList,
13920
13935
  motionPlayMode: params.motionPlayMode
13921
13936
  });
13922
- _c.label = 2;
13923
- case 2:
13924
- _c.trys.push([2, 4,, 5]);
13925
- apiUrl = "".concat(ConfigManager.getInstance().getApiBaseUrl(true)).concat(this.getBroadcastApiPath(params.type));
13926
- requestBody = {
13927
- humanCode: params.humanCode,
13928
- speed: params.speed,
13929
- volume: params.volume >= 0 ? params.volume * 100 : undefined,
13930
- // 转换为百分比
13931
- isSubtitle: params.isSubtitle
13932
- };
13933
- // 根据播报类型设置特定参数
13934
- if (params.type === exports.BroadcastType.TEXT) {
13935
- requestBody.text = params.text;
13936
- requestBody.voiceCode = params.voiceCode;
13937
- } else if (params.type === exports.BroadcastType.AUDIO) {
13938
- requestBody.text = params.text;
13939
- requestBody.audioUrl = params.audioUrl;
13940
- }
13941
- this.logger.debug('Sending broadcast request', {
13942
- apiUrl: apiUrl,
13943
- requestBody: requestBody
13944
- });
13945
13937
  // 触发开始回调
13946
13938
  (_b = (_a = this.callbacks).onStart) === null || _b === void 0 ? void 0 : _b.call(_a);
13947
13939
  this.isGeneratingAudio = true;
13948
- // 发起流式播报请求
13949
- return [4 /*yield*/, fetchEventSource(apiUrl, {
13950
- method: 'POST',
13951
- headers: {
13952
- 'Content-Type': 'application/json',
13953
- 'x_auth_token': ConfigManager.getInstance().getToken()
13954
- },
13955
- body: JSON.stringify(requestBody),
13956
- signal: this.activeController.signal,
13957
- openWhenHidden: true,
13958
- onmessage: function onmessage(event) {
13959
- var response = JSON.parse(event.data);
13960
- // 错误处理
13961
- if (response.code !== 0) {
13962
- _this.handleBroadcastError(response.code);
13963
- return;
13964
- }
13965
- // 流式播报
13966
- if (response.data) {
13967
- // 未完成播报时,更新任务ID
13968
- if (!response.data.done) {
13969
- _this.hasReceivedAudio = true;
13970
- }
13971
- // 自定义音频播报时,如果服务器未返回音频URL,使用传入的audioUrl
13972
- if (params.type === exports.BroadcastType.AUDIO && params.audioUrl && !response.data.voiceUrl) {
13973
- response.data.voiceUrl = params.audioUrl;
13974
- }
13975
- // 如果有音频URL,发送到Unity
13976
- if (response.data.voiceUrl) {
13977
- _this.sendMessage('AppendBroadcast', {
13978
- response: response,
13979
- callbackFun: _this.uniqueCallbackName,
13980
- operationType: exports.BroadcastOperationType.APPEND_BROADCAST
13981
- });
13982
- }
13983
- if (response.data.done) {
13984
- _this.isGeneratingAudio = false;
13985
- _this.hasReceivedAudio = false;
13986
- _this.activeController = null;
13987
- }
13988
- }
13989
- },
13990
- onclose: function onclose() {
13991
- var _a;
13992
- // 如果不是由abort触发的关闭,需要处理
13993
- if (_this.isGeneratingAudio) {
13994
- (_a = _this.activeController) === null || _a === void 0 ? void 0 : _a.abort();
13995
- }
13996
- // 流结束时调用完成回调
13997
- _this.logger.debug('Broadcast stream closed');
13998
- },
13999
- onerror: function onerror(error) {
14000
- _this.logger.error('Broadcast stream error', error);
14001
- var sdkError = new SDKError(exports.OperationErrorCode.OPERATION_FAILED, '服务出错了', error);
14002
- _this.handleError(sdkError);
14003
- // 必须抛出错误,否则会循环重试请求
14004
- throw new Error("\u670D\u52A1\u51FA\u9519\u4E86".concat(sdkError.message));
14005
- }
14006
- })];
14007
- case 3:
14008
- // 发起流式播报请求
14009
- _c.sent();
14010
- return [3 /*break*/, 5];
14011
- case 4:
14012
- error_1 = _c.sent();
14013
- this.handleError(error_1);
14014
- return [3 /*break*/, 5];
14015
- case 5:
13940
+ _c.label = 2;
13941
+ case 2:
13942
+ task = this.createBroadcastTask(params);
13943
+ // 添加任务到队列
13944
+ this.addTaskToQueue(task);
13945
+ this.logger.debug('Broadcast task created and queued', {
13946
+ taskId: task.id,
13947
+ sequence: task.sequence,
13948
+ isAppend: isAppend
13949
+ });
14016
13950
  return [2 /*return*/];
14017
13951
  }
14018
13952
  });
@@ -14030,7 +13964,7 @@
14030
13964
  */
14031
13965
  BroadcastService.prototype.pauseBroadcast = function (resetIdle) {
14032
13966
  return __awaiter(this, void 0, void 0, function () {
14033
- var error_2;
13967
+ var error_1;
14034
13968
  return __generator(this, function (_a) {
14035
13969
  switch (_a.label) {
14036
13970
  case 0:
@@ -14046,9 +13980,9 @@
14046
13980
  this.logger.info('Broadcast paused successfully');
14047
13981
  return [3 /*break*/, 4];
14048
13982
  case 3:
14049
- error_2 = _a.sent();
14050
- this.logger.error('Failed to pause broadcast', error_2);
14051
- throw error_2;
13983
+ error_1 = _a.sent();
13984
+ this.logger.error('Failed to pause broadcast', error_1);
13985
+ throw error_1;
14052
13986
  case 4:
14053
13987
  return [2 /*return*/];
14054
13988
  }
@@ -14066,7 +14000,7 @@
14066
14000
  */
14067
14001
  BroadcastService.prototype.resumeBroadcast = function () {
14068
14002
  return __awaiter(this, void 0, void 0, function () {
14069
- var error_3;
14003
+ var error_2;
14070
14004
  return __generator(this, function (_a) {
14071
14005
  switch (_a.label) {
14072
14006
  case 0:
@@ -14080,9 +14014,9 @@
14080
14014
  this.logger.info('Broadcast resumed successfully');
14081
14015
  return [3 /*break*/, 4];
14082
14016
  case 3:
14083
- error_3 = _a.sent();
14084
- this.logger.error('Failed to resume broadcast', error_3);
14085
- throw error_3;
14017
+ error_2 = _a.sent();
14018
+ this.logger.error('Failed to resume broadcast', error_2);
14019
+ throw error_2;
14086
14020
  case 4:
14087
14021
  return [2 /*return*/];
14088
14022
  }
@@ -14100,16 +14034,18 @@
14100
14034
  */
14101
14035
  BroadcastService.prototype.stopBroadcast = function () {
14102
14036
  return __awaiter(this, void 0, void 0, function () {
14103
- var error_4;
14037
+ var error_3;
14104
14038
  return __generator(this, function (_a) {
14105
14039
  switch (_a.label) {
14106
14040
  case 0:
14107
- this.logger.info('Stopping broadcast');
14108
- // 取消流式请求
14109
- if (this.activeController) {
14110
- this.activeController.abort();
14111
- this.activeController = null;
14112
- }
14041
+ this.logger.info('Stopping broadcast and clearing queue', {
14042
+ queueLength: this.taskQueue.length
14043
+ });
14044
+ // 取消所有队列中的任务
14045
+ this.cancelAllTasks();
14046
+ // 重置状态
14047
+ this.isGeneratingAudio = false;
14048
+ this.hasReceivedAudio = false;
14113
14049
  _a.label = 1;
14114
14050
  case 1:
14115
14051
  _a.trys.push([1, 3,, 4]);
@@ -14119,9 +14055,9 @@
14119
14055
  this.logger.info('Broadcast stopped successfully');
14120
14056
  return [3 /*break*/, 4];
14121
14057
  case 3:
14122
- error_4 = _a.sent();
14123
- this.logger.error('Failed to stop broadcast', error_4);
14124
- throw error_4;
14058
+ error_3 = _a.sent();
14059
+ this.logger.error('Failed to stop broadcast', error_3);
14060
+ throw error_3;
14125
14061
  case 4:
14126
14062
  return [2 /*return*/];
14127
14063
  }
@@ -14140,15 +14076,31 @@
14140
14076
  /**
14141
14077
  * 获取播报状态
14142
14078
  * @returns 播报状态信息
14143
- * @description 获取当前播报服务的状态信息
14079
+ * @description 获取当前播报服务的状态信息,包括队列状态
14144
14080
  */
14145
14081
  BroadcastService.prototype.getStatus = function () {
14146
14082
  return {
14147
- isActive: this.activeController !== null,
14083
+ isActive: this.taskQueue.length > 0 || this.isGeneratingAudio,
14148
14084
  isGeneratingAudio: this.isGeneratingAudio,
14149
14085
  hasReceivedAudio: this.hasReceivedAudio,
14150
14086
  pendingCallbacks: this.getPendingCallbackCount(),
14151
- hasController: this.activeController !== null
14087
+ hasController: this.activeController !== null,
14088
+ queueInfo: {
14089
+ totalTasks: this.taskQueue.length,
14090
+ requestingTasks: this.taskQueue.filter(function (t) {
14091
+ return t.status === BroadcastTaskStatus.REQUESTING;
14092
+ }).length,
14093
+ completedTasks: this.taskQueue.filter(function (t) {
14094
+ return t.status === BroadcastTaskStatus.COMPLETED;
14095
+ }).length,
14096
+ failedTasks: this.taskQueue.filter(function (t) {
14097
+ return t.status === BroadcastTaskStatus.FAILED;
14098
+ }).length,
14099
+ totalPendingResponses: this.taskQueue.reduce(function (sum, t) {
14100
+ return sum + t.pendingResponses.length;
14101
+ }, 0),
14102
+ currentSendingSequence: this.currentSendingSequence
14103
+ }
14152
14104
  };
14153
14105
  };
14154
14106
  /**
@@ -14156,15 +14108,308 @@
14156
14108
  * @description 清理所有资源和回调
14157
14109
  */
14158
14110
  BroadcastService.prototype.destroy = function () {
14159
- // 停止当前播报
14160
- if (this.activeController) {
14161
- this.activeController.abort();
14162
- this.activeController = null;
14111
+ // 清理队列处理定时器
14112
+ if (this.queueProcessTimer) {
14113
+ clearInterval(this.queueProcessTimer);
14114
+ this.queueProcessTimer = null;
14163
14115
  }
14116
+ // 取消所有任务
14117
+ this.cancelAllTasks();
14164
14118
  // 调用基类销毁方法
14165
14119
  _super.prototype.destroy.call(this);
14166
14120
  this.logger.info('Broadcast service destroyed');
14167
14121
  };
14122
+ /**
14123
+ * 创建播报任务
14124
+ * @param params - 播报参数
14125
+ * @returns IBroadcastTask 播报任务对象
14126
+ * @description 创建新的播报任务并分配唯一ID和序号
14127
+ * @private
14128
+ */
14129
+ BroadcastService.prototype.createBroadcastTask = function (params) {
14130
+ var task = {
14131
+ id: "broadcast_".concat(Date.now(), "_").concat(Math.random().toString(36).substring(2, 9)),
14132
+ sequence: ++this.taskSequence,
14133
+ params: params,
14134
+ status: BroadcastTaskStatus.REQUESTING,
14135
+ controller: new AbortController(),
14136
+ pendingResponses: [],
14137
+ isGenerationComplete: false,
14138
+ createdAt: new Date()
14139
+ };
14140
+ this.logger.debug('Created broadcast task', {
14141
+ taskId: task.id,
14142
+ sequence: task.sequence
14143
+ });
14144
+ return task;
14145
+ };
14146
+ /**
14147
+ * 添加任务到队列
14148
+ * @param task - 播报任务
14149
+ * @description 将任务添加到队列并立即开始请求
14150
+ * @private
14151
+ */
14152
+ BroadcastService.prototype.addTaskToQueue = function (task) {
14153
+ this.taskQueue.push(task);
14154
+ this.logger.debug('Task added to queue', {
14155
+ taskId: task.id,
14156
+ queueLength: this.taskQueue.length
14157
+ });
14158
+ // 立即开始该任务的请求
14159
+ this.startTaskRequest(task);
14160
+ // 开始处理队列
14161
+ this.processQueue();
14162
+ };
14163
+ /**
14164
+ * 处理队列
14165
+ * @description 处理队列中的任务,发起请求生成音频
14166
+ * @private
14167
+ */
14168
+ BroadcastService.prototype.processQueue = function () {
14169
+ var _this = this;
14170
+ // 启动队列处理定时器(如果尚未启动)
14171
+ if (!this.queueProcessTimer) {
14172
+ this.queueProcessTimer = setInterval(function () {
14173
+ _this.processQueueStep();
14174
+ }, 100); // 每100ms检查一次队列状态
14175
+ }
14176
+ // 立即处理一次
14177
+ this.processQueueStep();
14178
+ };
14179
+ /**
14180
+ * 队列处理步骤
14181
+ * @description 处理队列中的单个步骤,包括发起请求和发送音频
14182
+ * @private
14183
+ */
14184
+ BroadcastService.prototype.processQueueStep = function () {
14185
+ var _this = this;
14186
+ // 按序号找到下一个要处理的任务
14187
+ var nextTask = this.taskQueue.find(function (task) {
14188
+ return task.sequence === _this.currentSendingSequence + 1 && task.pendingResponses.length > 0;
14189
+ });
14190
+ if (nextTask) {
14191
+ this.sendNextResponse(nextTask);
14192
+ }
14193
+ // 清理已完成的任务
14194
+ this.cleanupCompletedTasks();
14195
+ // 如果队列为空,停止定时器
14196
+ if (this.taskQueue.length === 0 && this.queueProcessTimer) {
14197
+ clearInterval(this.queueProcessTimer);
14198
+ this.queueProcessTimer = null;
14199
+ }
14200
+ };
14201
+ /**
14202
+ * 开始任务请求
14203
+ * @param task - 播报任务
14204
+ * @description 为任务发起流式请求生成音频
14205
+ * @private
14206
+ */
14207
+ BroadcastService.prototype.startTaskRequest = function (task) {
14208
+ return __awaiter(this, void 0, void 0, function () {
14209
+ var apiUrl, requestBody;
14210
+ var _this = this;
14211
+ return __generator(this, function (_a) {
14212
+ task.status = BroadcastTaskStatus.REQUESTING;
14213
+ this.logger.debug('Starting task request', {
14214
+ taskId: task.id
14215
+ });
14216
+ try {
14217
+ apiUrl = "".concat(ConfigManager.getInstance().getApiBaseUrl(true)).concat(this.getBroadcastApiPath(task.params.type));
14218
+ requestBody = {
14219
+ humanCode: task.params.humanCode,
14220
+ speed: task.params.speed,
14221
+ volume: task.params.volume >= 0 ? task.params.volume * 100 : undefined,
14222
+ isSubtitle: task.params.isSubtitle
14223
+ };
14224
+ // 根据播报类型设置特定参数
14225
+ if (task.params.type === exports.BroadcastType.TEXT) {
14226
+ requestBody.text = task.params.text;
14227
+ requestBody.voiceCode = task.params.voiceCode;
14228
+ } else if (task.params.type === exports.BroadcastType.AUDIO) {
14229
+ requestBody.text = task.params.text;
14230
+ requestBody.audioUrl = task.params.audioUrl;
14231
+ }
14232
+ // 发起流式请求
14233
+ fetchEventSource(apiUrl, {
14234
+ method: 'POST',
14235
+ headers: {
14236
+ 'Content-Type': 'application/json',
14237
+ 'x_auth_token': ConfigManager.getInstance().getToken()
14238
+ },
14239
+ body: JSON.stringify(requestBody),
14240
+ signal: task.controller.signal,
14241
+ openWhenHidden: true,
14242
+ onmessage: function onmessage(event) {
14243
+ _this.handleTaskResponse(task, event.data);
14244
+ },
14245
+ onclose: function onclose() {
14246
+ _this.handleTaskClose(task);
14247
+ },
14248
+ onerror: function onerror(error) {
14249
+ _this.handleTaskError(task, error);
14250
+ throw new Error("Task ".concat(task.id, " request failed: ").concat(error));
14251
+ }
14252
+ });
14253
+ } catch (error) {
14254
+ this.handleTaskError(task, error);
14255
+ }
14256
+ return [2 /*return*/];
14257
+ });
14258
+ });
14259
+ };
14260
+ /**
14261
+ * 处理任务响应
14262
+ * @param task - 播报任务
14263
+ * @param data - 响应数据
14264
+ * @description 处理任务的流式响应数据
14265
+ * @private
14266
+ */
14267
+ BroadcastService.prototype.handleTaskResponse = function (task, data) {
14268
+ try {
14269
+ var response = JSON.parse(data);
14270
+ // 错误处理
14271
+ if (response.code !== 0) {
14272
+ this.handleBroadcastError(response.code);
14273
+ return;
14274
+ }
14275
+ // 处理音频数据
14276
+ if (response.data && response.data.voiceUrl) {
14277
+ // 自定义音频播报时,如果服务器未返回音频URL,使用传入的audioUrl
14278
+ if (task.params.type === exports.BroadcastType.AUDIO && task.params.audioUrl && !response.data.voiceUrl) {
14279
+ response.data.voiceUrl = task.params.audioUrl;
14280
+ }
14281
+ // 添加处理后的响应对象到待发送队列
14282
+ task.pendingResponses.push(response);
14283
+ this.logger.debug('Response added to task', {
14284
+ taskId: task.id,
14285
+ pendingCount: task.pendingResponses.length
14286
+ });
14287
+ }
14288
+ // 检查是否完成
14289
+ if (response.data && response.data.done) {
14290
+ task.isGenerationComplete = true;
14291
+ this.logger.debug('Task generation completed', {
14292
+ taskId: task.id,
14293
+ totalResponses: task.pendingResponses.length
14294
+ });
14295
+ // 任务完成生成,保持REQUESTING状态直到所有响应发送完毕
14296
+ }
14297
+ } catch (error) {
14298
+ this.handleTaskError(task, error);
14299
+ }
14300
+ };
14301
+ /**
14302
+ * 发送下一个响应
14303
+ * @param task - 播报任务
14304
+ * @description 发送任务中的第一个待发送响应到Unity,发送后立即删除
14305
+ * @private
14306
+ */
14307
+ BroadcastService.prototype.sendNextResponse = function (task) {
14308
+ var _a;
14309
+ if (task.pendingResponses.length === 0) {
14310
+ return;
14311
+ }
14312
+ // 取出第一个待发送的响应
14313
+ var response = task.pendingResponses.shift();
14314
+ this.logger.debug('Sending response to Unity', {
14315
+ taskId: task.id,
14316
+ remainingResponses: task.pendingResponses.length,
14317
+ voiceUrl: (_a = response.data) === null || _a === void 0 ? void 0 : _a.voiceUrl
14318
+ });
14319
+ // 发送响应到Unity
14320
+ this.sendMessage('AppendBroadcast', {
14321
+ response: response,
14322
+ callbackFun: this.uniqueCallbackName,
14323
+ operationType: exports.BroadcastOperationType.APPEND_BROADCAST
14324
+ });
14325
+ // 如果任务已完成且没有更多待发送响应,标记任务完成并推进序号
14326
+ if (task.isGenerationComplete && task.pendingResponses.length === 0) {
14327
+ task.status = BroadcastTaskStatus.COMPLETED;
14328
+ this.currentSendingSequence = task.sequence;
14329
+ this.logger.debug('Task completed', {
14330
+ taskId: task.id
14331
+ });
14332
+ }
14333
+ };
14334
+ /**
14335
+ * 处理任务关闭
14336
+ * @param task - 播报任务
14337
+ * @description 处理任务的流式连接关闭
14338
+ * @private
14339
+ */
14340
+ BroadcastService.prototype.handleTaskClose = function (task) {
14341
+ this.logger.debug('Task stream closed', {
14342
+ taskId: task.id
14343
+ });
14344
+ // 如果还没有标记为完成,则标记为完成
14345
+ if (!task.isGenerationComplete && task.status === BroadcastTaskStatus.REQUESTING) {
14346
+ task.isGenerationComplete = true;
14347
+ }
14348
+ };
14349
+ /**
14350
+ * 处理任务错误
14351
+ * @param task - 播报任务
14352
+ * @param error - 错误对象
14353
+ * @description 处理任务执行过程中的错误
14354
+ * @private
14355
+ */
14356
+ BroadcastService.prototype.handleTaskError = function (task, error) {
14357
+ var _a, _b;
14358
+ task.status = BroadcastTaskStatus.FAILED;
14359
+ task.error = error;
14360
+ this.logger.error("Task failed - ".concat(task.id), error);
14361
+ // 触发错误回调
14362
+ (_b = (_a = this.callbacks).onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
14363
+ };
14364
+ /**
14365
+ * 清理已完成的任务
14366
+ * @description 从队列中移除已完成、失败或取消的任务
14367
+ * @private
14368
+ */
14369
+ BroadcastService.prototype.cleanupCompletedTasks = function () {
14370
+ var beforeLength = this.taskQueue.length;
14371
+ this.taskQueue = this.taskQueue.filter(function (task) {
14372
+ return task.status !== BroadcastTaskStatus.COMPLETED && task.status !== BroadcastTaskStatus.FAILED && task.status !== BroadcastTaskStatus.CANCELLED;
14373
+ });
14374
+ var removedCount = beforeLength - this.taskQueue.length;
14375
+ if (removedCount > 0) {
14376
+ this.logger.debug('Cleaned up completed tasks', {
14377
+ removedCount: removedCount,
14378
+ remainingTasks: this.taskQueue.length
14379
+ });
14380
+ }
14381
+ };
14382
+ /**
14383
+ * 取消所有任务
14384
+ * @description 取消队列中的所有任务
14385
+ * @private
14386
+ */
14387
+ BroadcastService.prototype.cancelAllTasks = function () {
14388
+ var e_1, _a;
14389
+ try {
14390
+ for (var _b = __values(this.taskQueue), _c = _b.next(); !_c.done; _c = _b.next()) {
14391
+ var task = _c.value;
14392
+ if (task.status !== BroadcastTaskStatus.COMPLETED && task.status !== BroadcastTaskStatus.FAILED) {
14393
+ task.controller.abort();
14394
+ task.status = BroadcastTaskStatus.CANCELLED;
14395
+ }
14396
+ }
14397
+ } catch (e_1_1) {
14398
+ e_1 = {
14399
+ error: e_1_1
14400
+ };
14401
+ } finally {
14402
+ try {
14403
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
14404
+ } finally {
14405
+ if (e_1) throw e_1.error;
14406
+ }
14407
+ }
14408
+ this.taskQueue = [];
14409
+ this.taskSequence = 0;
14410
+ this.currentSendingSequence = 0;
14411
+ this.logger.debug('All tasks cancelled and queue cleared');
14412
+ };
14168
14413
  Object.defineProperty(BroadcastService.prototype, "callbackFunctionName", {
14169
14414
  /** 全局回调函数名称 */
14170
14415
  get: function get() {