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