import {_decorator, Button, Component, EditBox, instantiate, Label, Node, Prefab, RichText, ScrollView, System, Toggle, ToggleContainerComponent, UITransform} from 'cc';

import {ITMG_AUDIO_RECORDING_CONTENT, ITMG_KARAOKE_TYPE} from '../GMESDK/Scripts/TMGAudioEffectCtrl';
import {GetAuthBuffer, GetTMGInstance, TMGContext, TMGDelegate} from '../GMESDK/Scripts/TMGContext';
import {ITMG_APP_SCENE, ITMG_AUDIO_MEMBER_ROLE, ITMG_LOG_LEVEL, ITMG_MAIN_EVENT_TYPE, ITMG_RANGE_AUDIO_MODE, ITMG_ROOM_TYPE, ITMG_VOICE_TYPE, TMGAudioDeviceInfo} from '../GMESDK/Scripts/TMGType';

import {UpdatePostion} from './updatePostion';

const {ccclass, property} = _decorator;

export class TMGDelegateImpl implements TMGDelegate {
  constructor(apiTestInstance: APITest) {
    this.apiTestInstance = apiTestInstance;
  }

  OnEvent(type: ITMG_MAIN_EVENT_TYPE, data: string): void {
    if (this.apiTestInstance != null) {
      this.apiTestInstance.OnEvent(type, data);
    }
  }

  public apiTestInstance: APITest|null = null;
}


class ApiFuncObj {
  funcName: string;
  handleClickName: string;
  funcDescription: string;
  constructor(funcName: string, handleClickName: string, funcDescription: string) {
    this.funcName = funcName;
    this.handleClickName = handleClickName;
    this.funcDescription = funcDescription;
  }
}

@ccclass('APITest')
export class APITest extends Component {
  @property(cc.Node) currentSceneNode: cc.Node = null;  // 当前场景的根节点

  @property(cc.Node) updatePositionNode: cc.Node = null;  // 新场景的根节点

  @property(ScrollView)  // 绑定 ScrollView 组件
  scrollView: ScrollView = null;
  @property(Prefab)  // 绑定 Button 预制体
  buttonPrefab: Prefab = null;
  @property(Prefab) richTextPrefab: Prefab = null;



  @property(ScrollView)  // 绑定 ScrollView 控件
  private callbackInfoScrollView: ScrollView|null = null;

  @property(Label)  // 绑定 Label 控件
  private callbackInfoLabel: Label|null = null;

  @property(ScrollView) private apiResultScrollView: ScrollView|null = null;
  @property(Label) private ApiResultLabel: Label|null = null;


  @property(EditBox) public AppidEditBox: EditBox|null = null;
  @property(EditBox) public KeyEditBox: EditBox|null = null;
  @property(EditBox) public UserIdEditBox: EditBox|null = null;
  @property(EditBox) public RoomIdEditBox: EditBox|null = null;
  @property(ToggleContainerComponent) public SceneToggleGroup: ToggleContainerComponent|null = null;
  @property(ToggleContainerComponent)
  public AudioRoleToggleGroup: ToggleContainerComponent|null = null;
  @property(ToggleContainerComponent)
  public RoomTypeToggleGroup: ToggleContainerComponent|null = null;

  @property(Toggle) public InitToggle: Toggle|null = null;
  @property(Toggle) public EnterRoomToggle: Toggle|null = null;

  @property(Toggle) public EnableMicToggle: Toggle|null = null;
  @property(Toggle) public EnableSpeakToggle: Toggle|null = null;
  @property(Toggle) public EnableLoopbackToggle: Toggle|null = null;
  @property(EditBox) public CallBackInfoEditBox: EditBox|null = null;

  private tmgContext: TMGContext|null;
  private tmgDelegate: TMGDelegate|null;
  private apiContent: Node|null;
  private apiSeq: number = 0;
  private lines: string[] = [];   // 存储每一行的文字
  private maxLines: number = 10;  // 最大行数


  private apiResultLines: string[] = [];   // 存储每一行的文字
  private apiResultMaxLines: number = 10;  // 最大行数

  apiList: {[key: string]: ApiFuncObj[]} = {}

  private recordFilePath: string = '';
  private pttFilePath: string = '';
  private pttFileId: string = '';
  private pttText: string = '测试gme文本翻译功能';
  private isPrintfHighFrequencyLog = true;

  OnEvent(type: ITMG_MAIN_EVENT_TYPE, data: string): void {
    if (!this.isPrintfHighFrequencyLog && type == ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_NETWORK_QUALITY) {
      return;
    }
    const logMessage = `Event: type=${type}, data=${data}\n`;
    this.showCallbackInfo(logMessage);
    switch (type) {
      case ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_RECORD_COMPLETE: {
        const jsonObject = JSON.parse(data);
        if (jsonObject.result == 0 && jsonObject.file_path != null) {
          this.pttFilePath = jsonObject.file_path;
        }
      } break;

      case ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_UPLOAD_COMPLETE: {
        const jsonObject = JSON.parse(data);
        if (jsonObject.result == 0 && jsonObject.file_id != null) {
          this.pttFileId = jsonObject.file_id;
        }
      } break;

      case ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_DOWNLOAD_COMPLETE: {
        const jsonObject = JSON.parse(data);
        if (jsonObject.result == 0 && jsonObject.file_path != null) {
          this.pttFilePath = jsonObject.file_path;
        }
        if (jsonObject.result == 0 && jsonObject.file_id != null) {
          this.pttFileId = jsonObject.file_id;
        }
      } break;

      case ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_STREAMINGRECOGNITION_COMPLETE: {
        const jsonObject = JSON.parse(data);

        if (jsonObject.result != 0) {
          return;
        }
        if (jsonObject.file_path != null) {
          this.pttFilePath = jsonObject.file_path;
        }
        if (jsonObject.result == 0 && jsonObject.file_id != null) {
          this.pttFileId = jsonObject.file_id;
        }
      } break;
      case ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_TEXT2SPEECH_COMPLETE: {
        const jsonObject = JSON.parse(data);
       if (jsonObject.result == 0 && jsonObject.file_id != null) {
          this.pttFileId = jsonObject.file_id;
        }
      } break;
      case ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_EXIT_ROOM: {
        this.uninitEventHandlers();
        this.EnterRoomToggle.isChecked = false;
        this.EnableMicToggle.isChecked = false;
        this.EnableSpeakToggle.isChecked = false;
        this.EnableLoopbackToggle.isChecked = false;
        this.setupEventHandlers();
      } break;
      case ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_ENTER_ROOM: {
        this.uninitEventHandlers();
        this.EnterRoomToggle.isChecked = true;
        this.setupEventHandlers();
      } break;
      case ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_ROOM_DISCONNECT: {
        this.uninitEventHandlers();
        this.EnterRoomToggle.isChecked = false;
        this.EnableMicToggle.isChecked = false;
        this.EnableSpeakToggle.isChecked = false;
        this.EnableLoopbackToggle.isChecked = false;
        this.setupEventHandlers();
      } break;
    }
  }

  showCallbackInfo(info: string) {
    const maxBytesPerLine = 100;
    let resultLines = [];
    let currentLine = '';

    for (let i = 0; i < info.length; i++) {
      currentLine += info[i];
      if (currentLine.length >= maxBytesPerLine) {
        resultLines.push(currentLine);
        currentLine = '';
      }
    }

    if (currentLine.length > 0) {
      resultLines.push(currentLine);
    }

    resultLines.forEach(line => {
      this.addLine(line);
    });
  }

  generateRandomNumberString(length) {
    let result = '';
    for (let i = 0; i < length; i++) {
      let randomDigit = Math.floor(Math.random() * 10);
      result += randomDigit.toString();
    }
    return result;
  }

  start() {
    this.AppidEditBox.string = AppID To Replace Here https://cloud.tencent.com/document/product/607/10782;
    this.KeyEditBox.string = AppKey To Replace Here https://cloud.tencent.com/document/product/607/10782;
    this.UserIdEditBox.string = this.generateRandomNumberString(6);
    this.RoomIdEditBox.string = '20250601';
    this.apiContent = this.scrollView.content;
    this.apiSeq = 0;
    this.tmgContext = GetTMGInstance();
    this.tmgDelegate = new TMGDelegateImpl(this);
    this.tmgContext.SetTMGDelegate(this.tmgDelegate);
    this.initApiList();
    this.setupEventHandlers();

    this.addAPITestButton();

    this.callbackInfoLabel.string = '';

    if (cc.sys.os === cc.sys.OS_ANDROID) {
      let hasPermission = jsb.reflection.callStaticMethod(
          'com/cocos/game/AppActivity', 'checkPermission', '(Ljava/lang/String;)Z',
          'android.permission.RECORD_AUDIO');

      if (!hasPermission) {
        jsb.reflection.callStaticMethod(
            'com/cocos/game/AppActivity', 'requestPermission', '(Ljava/lang/String;)V',
            'android.permission.RECORD_AUDIO');
      }
    }

    this.recordFilePath = jsb.fileUtils.getWritablePath();

    cc.game.on(cc.Game.EVENT_HIDE, this.onGameHide, this);
    cc.game.on(cc.Game.EVENT_SHOW, this.onGameShow, this);
  }

  update() {
    if (this.tmgContext) {
      this.tmgContext.Poll();
    }
  }

  private onGameHide() {
    this.tmgContext.Pause();
  }

  private onGameShow() {
    this.tmgContext.Resume();
  }

  addLine(text: string) {
    if (!this.callbackInfoLabel || !this.scrollView)
      return;
    this.lines.push(text);
    if (this.lines.length > this.maxLines) {
      this.lines.shift();
    }
    this.callbackInfoLabel.string = this.lines.join('\n');

    // 滚动到底部
    this.scrollToBottom();
  }

  /**
   * 滚动到底部
   */
  private scrollToBottom() {
    if (!this.callbackInfoScrollView)
      return;

    // 获取 ScrollView 的 content 节点
    const content = this.callbackInfoScrollView.content;
    if (content) {
      // 设置滚动位置为底部
      const lineHeight = 10;
      const height = (this.maxLines - this.lines.length) * lineHeight + 100;
      this.callbackInfoScrollView.scrollToBottom(height);  // 0.1 秒内滚动到底部
    }
  }

  /**
   * 清空所有文字
   */
  clearLines() {
    this.lines = [];  // 清空 lines 数组
    if (this.callbackInfoLabel) {
      this.callbackInfoLabel.string = '';  // 清空 Label 的文字
    }
  }

  printApiResult(info: string) {
    const maxBytesPerLine = 100;
    let resultLines = [];
    let currentLine = '';

    for (let i = 0; i < info.length; i++) {
      currentLine += info[i];
      // 使用字符串的length属性替代Buffer.byteLength
      if (currentLine.length >= maxBytesPerLine) {
        resultLines.push(currentLine);
        currentLine = '';
      }
    }

    if (currentLine.length > 0) {
      resultLines.push(currentLine);
    }

    // 将分割后的每行内容传递给addLine
    resultLines.forEach(line => {
      this.addApiResult(line);
    });
  }

  addApiResult(text: string) {
    if (!this.ApiResultLabel || !this.scrollView)
      return;
    this.apiResultLines.push(text);
    if (this.apiResultLines.length > this.apiResultMaxLines) {
      this.apiResultLines.shift();
    }
    this.ApiResultLabel.string = this.apiResultLines.join('\n');

    // 滚动到底部
    this.apiResultscrollToBottom();
  }

  /**
   * 滚动到底部
   */
  private apiResultscrollToBottom() {
    if (!this.apiResultScrollView)
      return;

    // 获取 ScrollView 的 content 节点
    const content = this.apiResultScrollView.content;
    if (content) {
      // 设置滚动位置为底部
      const lineHeight = 15;
      const height = this.apiResultLines.length * lineHeight;
      this.apiResultScrollView.scrollToBottom(height);  // 0.1 秒内滚动到底部
    }
  }

  initApiList() {
    this.apiList['TMGContext'] = [
      new ApiFuncObj('SetRegion', 'SetRegionDEFAULT_TESTClick', '设置接入点-DEFAULT_TEST'),
      new ApiFuncObj('SetRegion', 'SetRegionDEFAULTClick', '设置接入点-DEFAULT'),
      new ApiFuncObj(
          'SetRangeAudioMode', 'SetRangeAudioModeClick', '设置范围语音模式-SND_TEAM_REC_TEAM'),
      new ApiFuncObj('SetRangeAudioTeamID', 'SetRangeAudioTeamID2Click', '设置范围语音的 TeamID-2'),
      new ApiFuncObj('SetRangeAudioTeamID', 'SetRangeAudioTeamID0Click', '设置范围语音的 TeamID-0'),
      new ApiFuncObj('IsRoomEntered', 'IsRoomEnteredClick', '是否已经在语音房间内'),
      new ApiFuncObj('SetLogLevel', 'SetLogLevelClick', '设置打印日志等级ERROR,ERROR'),
      new ApiFuncObj('SetLogPath', 'SetLogPathClick', '设置日志文件保存路径'),
      new ApiFuncObj('GetLogPath', 'GetLogPathClick', '获取日志文件保存路径'),
      new ApiFuncObj('GetSDKVersion', 'GetSDKVersionClick', '获取 GME SDK 版本'),
      new ApiFuncObj(
          'SetAppVersion', 'SetAppVersionClick', '设置 App 版本号-gme cocoscreator3.0.3'),
      new ApiFuncObj('SetRecvMixStreamCount', 'SetRecvMixStreamCountClick', '设置最大混音路数 5'),
      new ApiFuncObj('SetAdvanceParams', 'SetAdvanceParamsClick', '设置高级功能参数'),
      new ApiFuncObj('GetAdvanceParams', 'GetAdvanceParamsClick', '获取高级功能参数值'),
      new ApiFuncObj('CheckMicPermission', 'CheckMicPermissionClick', '查询麦克风权限'),
      new ApiFuncObj('ClosePrintfHighFrequencyLog', 'ClosePrintfHighFrequencyLogClick', 'demo关闭高频日志打印'),
      new ApiFuncObj('OpenPrintfHighFrequencyLog', 'OpenPrintfHighFrequencyLogClick', 'demo打开高频日志打印')
    ];

    this.apiList['TMGAudioCtrl'] = [
      new ApiFuncObj('GetMicState', 'GetMicStateClick', '麦克风状态获取'),
      new ApiFuncObj('GetSpeakerState', 'GetSpeakerStateClick', '扬声器状态获取'),
      new ApiFuncObj(
          'EnableAudioCaptureDevice-true', 'EnableAudioCaptureDeviceTrueClick', '开启音频采集设备'),
      new ApiFuncObj(
          'EnableAudioCaptureDevice-false', 'EnableAudioCaptureDeviceFalseClick',
          '关闭音频采集设备'),
      new ApiFuncObj(
          'IsAudioCaptureDeviceEnabled', 'IsAudioCaptureDeviceEnabledClick', '获取采集设备状态'),
      new ApiFuncObj(
          'EnableAudioPlayDevice-true', 'EnableAudioPlayDeviceTrueClick', '开启播放设备'),
      new ApiFuncObj(
          'EnableAudioPlayDevice-false', 'EnableAudioPlayDeviceFalseClick', '关闭播放设备'),
      new ApiFuncObj(
          'IsAudioPlayDeviceEnabled', 'IsAudioPlayDeviceEnabledClick', '获取播放设备状态'),
      new ApiFuncObj('EnableAudioSend', 'EnableAudioSendClick', '打开音频上行'),
      new ApiFuncObj('EnableAudioSend-false', 'EnableAudioSendFalseClick', '关闭音频上行'),
      new ApiFuncObj('IsAudioSendEnabled', 'IsAudioSendEnabledClick', '获取音频上行状态'),
      new ApiFuncObj('EnableAudioRecv-true', 'EnableAudioRecvTrueClick', '打开音频下行'),
      new ApiFuncObj('EnableAudioRecv-false', 'EnableAudioRecvFalseClick', '关闭音频下行'),
      new ApiFuncObj('IsAudioRecvEnabled', 'IsAudioRecvEnabledClick', '获取音频下行状态'),
      new ApiFuncObj('SetMicVolume', 'SetMicVolumeClick', '设置麦克风音量的增益-20'),
      new ApiFuncObj('GetMicVolume', 'GetMicVolumeClick', '获取麦克风音量的增益'),
      new ApiFuncObj('SetSpeakerVolume', 'SetSpeakerVolumeClick', '设置扬声器音量的增益-20'),
      new ApiFuncObj('GetSpeakerVolume', 'GetSpeakerVolumeClick', '获取扬声器音量的增益'),
      new ApiFuncObj(
          'SetSpeakerVolumeByUserID', 'SetSpeakerVolumeByUserIDClick',
          '动态设置房间内某成员-653的音量增益-20'),
      new ApiFuncObj(
          'GetSpeakerVolumeByUserID', 'GetSpeakerVolumeByUserIDClick', '获取某成员-653的音量增益'),
      new ApiFuncObj('AddAudioBlackList', 'AddAudioBlackListClick', '禁言房间中某个用户-653'),
      new ApiFuncObj(
          'RemoveAudioBlackList', 'RemoveAudioBlackListClick', '取消禁言房间中某个用户-653'),
      new ApiFuncObj(
          'IsUserIDInAudioBlackList', 'IsUserIDInAudioBlackListClick',
          '查询某个用户是否被禁言-653'),
      new ApiFuncObj('EnableSpatializer-true', 'EnableSpatializerTrueClick', '开启3D 音效'),
      new ApiFuncObj('EnableSpatializer-false', 'EnableSpatializerFalseClick', '关闭 3D 音效'),
      new ApiFuncObj('IsEnableSpatializer', 'IsEnableSpatializerClick', '获取当前 3D 音效状态'),
      new ApiFuncObj(
          'GetMicListCount', 'GetMicListCountClick', '获取麦克风设备数量-仅适用于桌面端'),
      new ApiFuncObj('GetMicList', 'GetMicListClick', '获取麦克风设备列表-仅适用于桌面端'),
      new ApiFuncObj('SelectMic', 'SelectMicClick', '选择麦克风设备-仅适用于桌面端'),
      new ApiFuncObj(
          'GetCurrentMic', 'GetCurrentMicClick', '获取当前使用的麦克风设备-仅适用于桌面端'),
      new ApiFuncObj(
          'GetSpeakerListCount', 'GetSpeakerListCountClick', '获取扬声器设备数量-仅适用于桌面端'),
      new ApiFuncObj('GetSpeakerList', 'GetSpeakerListClick', '获取扬声器设备列表-仅适用于桌面端'),
      new ApiFuncObj('SelectSpeaker', 'SelectSpeakerClick', '选择扬声器设备-仅适用于桌面端'),
      new ApiFuncObj(
          'GetCurrentSpeaker', 'GetCurrentSpeakerClick', '获取当前使用的扬声器设备-仅适用于桌面端'),
      new ApiFuncObj('SetAudioRoute', 'SetAudioRouteSPEAKERClick', '设置音频路由-SPEAKER'),
      new ApiFuncObj('SetAudioRoute', 'SetAudioRouteEARPIECEClick', '设置音频路由-EARPIECE'),
      new ApiFuncObj('TrackingVolume', 'TrackingVolumeClick', '开启音量回调-2s'),
      new ApiFuncObj('StopTrackingVolume', 'StopTrackingVolumeClick', '停止音量回调'),
      new ApiFuncObj('GetMicLevel', 'GetMicLevelClick', '获取实时麦克风音量'),
      new ApiFuncObj('GetSpeakerLevel', 'GetSpeakerLevelClick', '获取实时扬声器音量'),
      new ApiFuncObj('GetSendStreamLevel', 'GetSendStreamLevelClick', ' 获取音频上行实时音量'),
      new ApiFuncObj('GetRecvStreamLevel', 'GetRecvStreamLevelClick', '获取-653音频下行实时音量'),
      new ApiFuncObj(
          'StartMicDeviceTest', 'StartMicDeviceTestClick', '开始麦克风测试-仅桌面端有效'),
      new ApiFuncObj('StopMicDeviceTest', 'StopMicDeviceTestClick', '停止麦克风测试-仅桌面端有效'),
      new ApiFuncObj(
          'StartSpeakerDeviceTest', 'StartSpeakerDeviceTestClick', '开始扬声器测试-仅桌面端有效'),
      new ApiFuncObj(
          'StopSpeakerDeviceTest', 'StopSpeakerDeviceTestClick', '停止扬声器测试-仅桌面端有效')


    ];

    this.apiList['TMGRoom'] = [
      new ApiFuncObj('GetRoomID', 'GetRoomIDClick', '获取语音房间 ID'),
      new ApiFuncObj('ChangeRoomType', 'ChangeRoomTypeClick', '修改用户房间音频类型'),
      new ApiFuncObj('GetRoomType', 'GetRoomTypeClick', '获取用户房间音频类型'),
      new ApiFuncObj(
          'StartRoomSharing', 'StartRoomSharingClick', '开始跨房连麦通话roomid-888,userid-653'),
      new ApiFuncObj('StopRoomSharing', 'StopRoomSharingClick', '结束跨房连麦通话'),
      new ApiFuncObj('SwitchRoom', 'SwitchRoomClick', '快速切换房间roomid-888'),
      new ApiFuncObj('SendCustomData', 'SendCustomDataClick', '发送自定义消息-3次'),
      new ApiFuncObj('StopSendCustomData', 'StopSendCustomDataClick', '停止发送自定义消息'),
      new ApiFuncObj('UpdateAudioRecvRange', 'UpdateAudioRecvRangeClick', '设置接收语音距离范围-1'),
      new ApiFuncObj(
          'UpdateSpatializerRecvRange', 'UpdateSpatializerRecvRangeClick',
          '设置 3D 音效衰减距离-1'),
      new ApiFuncObj(
          'UpdateSelfOrOtherPosition', 'UpdateSelfOrOtherPositionClick',
          '更新玩家在指定房间的方位坐标'),
      new ApiFuncObj('SendSEIMsg', 'SendSEIMsgClick', '使用 SEI 通道发送自定义消息')
    ];

    this.apiList['TMGAudioEffectCtrl'] = [
      new ApiFuncObj('StartPlayMusic', 'StartPlayMusicClick', '开始播放背景音乐'),
      new ApiFuncObj('StopPlayMusic', 'StopPlayMusicClick', '停止播放背景音乐'),
      new ApiFuncObj('PausePlayMusic', 'PausePlayMusicClick', '暂停播放背景音乐'),
      new ApiFuncObj('ResumePlayMusic', 'ResumePlayMusicClick', '恢复播放背景音乐'),
      new ApiFuncObj('IsMusicPlayEnd', 'IsMusicPlayEndClick', '背景音乐是否播放结束'),
      new ApiFuncObj(
          'SetAllMusicVolume', 'SetAllMusicVolumeClick',
          '设置所有背景音乐的本地音量和远端音量的大小-20'),
      new ApiFuncObj(
          'SetMusicPublishVolume', 'SetMusicPublishVolume10Click',
          '设置某一首背景音乐的远端音量的大小-10'),
      new ApiFuncObj(
          'SetMusicPublishVolume', 'SetMusicPublishVolume100Click',
          '设置某一首背景音乐的远端音量的大小-100'),
      new ApiFuncObj(
          'GetMusicPublishVolume', 'GetMusicPublishVolumeClick',
          '获取某一首背景音乐的远端音量大小'),
      new ApiFuncObj(
          'SetMusicPlayoutVolume', 'SetMusicPlayoutVolume10Click',
          '控制某一首背景音乐的本地音量-10'),
      new ApiFuncObj(
          'SetMusicPlayoutVolume', 'SetMusicPlayoutVolume100Click',
          '控制某一首背景音乐的本地音量-100'),

      new ApiFuncObj(
          'GetMusicPlayoutVolume', 'GetMusicPlayoutVolumeClick',
          '获取某一首背景音乐的本地音量的大小'),
      new ApiFuncObj('SetMusicPitch', 'SetMusicPitch1Click', '调整背景音乐的音调高低为1'),
      new ApiFuncObj('SetMusicPitch', 'SetMusicPitchClick', '调整背景音乐的音调高低为-1'),

      new ApiFuncObj(
          'GetMusicDurationInMS', 'GetMusicDurationInMSClick', '获取背景音乐的总时长毫秒'),
      new ApiFuncObj(
          'GetMusicCurrentPosInMS', 'GetMusicCurrentPosInMSClick', '获取背景音乐的播放进度毫秒'),
      new ApiFuncObj(
          'SeekMusicToPosInTime', 'SeekMusicToPosInTimeClick', '设置背景音乐的播放进度毫秒- 16000'),
      new ApiFuncObj(
          'EnableMusicPublish', 'EnableMusicPublisClick', '将 sound_id 对应的背景音乐发布到远端'),
      new ApiFuncObj(
          'DisEnableMusicPublish', 'DisEnableMusicPublisClick',
          '取消将 sound_id 对应的背景音乐发布到远端'),
      new ApiFuncObj('EnableMusicPlayout', 'EnableMusicPlayoutClick', '开启本地播放当前背景音乐'),
      new ApiFuncObj(
          'DisEnableMusicPlayout', 'DisEnableMusicPlayoutClick', '取消本地播放当前背景音乐'),

      new ApiFuncObj('SetVoiceType', 'SetVoiceTypeClick', '设置人声的变声特效-LOLITA'),
      new ApiFuncObj('SetVoiceType-close', 'SetVoiceTypeCloseClick', '关闭人声变声特效'),

      new ApiFuncObj('SetKaraokeType-10', 'SetKaraokeTypeClick', '设置人声的混响特效-TYPE_10'),
      new ApiFuncObj('SetKaraokeType-close', 'SetKaraokeTypeCloseClick', '关闭人声混响特效'),

      new ApiFuncObj('StartRecordALL', 'StartRecordALLClick', '开始录制音频-ALL'),
      new ApiFuncObj('StartRecordLocal', 'StartRecordLocalClick', '开始录制音频-Local'),
      new ApiFuncObj('StartRecordRemote', 'StartRecordRemoteClick', '开始录制音频-Remote'),

      new ApiFuncObj('StopRecord', 'StopRecordClick', '停止录制音频'),
      new ApiFuncObj(
          'StartSystemAudioLoopback', 'StartSystemAudioLoopbackClick', '开启系统声音采集'),
      new ApiFuncObj('StopSystemAudioLoopback', 'StopSystemAudioLoopbackClick', '停止系统声音采集'),
      new ApiFuncObj(
          'SetSystemAudioLoopbackVolume', 'SetSystemAudioLoopbackVolume10Click',
          '设置系统声音的采集音量-10'),
    ];

    this.apiList['PTT'] = [
      new ApiFuncObj(
          'SetMaxMessageLength', 'SetMaxMessageLengthClick', '限制最大语音信息时长-180000'),
      new ApiFuncObj('StartRecording', 'StartRecordingClick', '启动录音'),
      new ApiFuncObj('StopRecording', 'StopRecordingClick', '停止录音'),
      new ApiFuncObj('CancelRecording', 'CancelRecordingClick', '取消录音'),
      new ApiFuncObj('UploadRecordedFile', 'UploadRecordedFileClick', '上传语音文件'),
      new ApiFuncObj('DownloadRecordedFile', 'DownloadRecordedFileClick', '下载语音文件'),
      new ApiFuncObj('PlayRecordedFile', 'PlayRecordedFileClick', '播放语音'),
      new ApiFuncObj('PlayRecordedFile', 'PlayRecordedFileVoiceTtpeClick', '播放语音-萝莉音'),
      new ApiFuncObj('StopPlayFile', 'StopPlayFileClick', '停止播放语音'),
      new ApiFuncObj('SpeechToText', 'SpeechToTextClick', '将指定的语音文件翻译成文字'),
      new ApiFuncObj('TranslateText', 'TranslateTextClick', '文本翻译接口。'),
      new ApiFuncObj('GetFileSize', 'GetFileSizeClick', '获取语音文件的大小'),
      new ApiFuncObj('GetVoiceFileDuration', 'GetVoiceFileDurationClick', '获取语音文件的时长'),
      new ApiFuncObj(
          'StartRecordingWithStreamingRecognition', 'StartRecordingWithStreamingRecognitionClick',
          '启动流式语音识别'),
      new ApiFuncObj(
          'SetPTTSourceLanguage', 'SetPTTSourceLanguageClick', '设置 PTT 功能源语言-en-US'),
      new ApiFuncObj('TextToSpeech', 'TextToSpeechClick', '文本转语音接口'),

    ];
  }

  private setupEventHandlers() {
    if (this.InitToggle) {
      this.InitToggle.node.on(Toggle.EventType.TOGGLE, this.onInitToggleChanged, this);
    }
    if (this.EnterRoomToggle) {
      this.EnterRoomToggle.node.on(Toggle.EventType.TOGGLE, this.onEnterRoomToggleChanged, this);
    }
    if (this.EnableMicToggle) {
      this.EnableMicToggle.node.on(Toggle.EventType.TOGGLE, this.onEnableMicToggleChanged, this);
    }
    if (this.EnableSpeakToggle) {
      this.EnableSpeakToggle.node.on(
          Toggle.EventType.TOGGLE, this.onEnableSpeakToggleChanged, this);
    }
    if (this.EnableLoopbackToggle) {
      this.EnableLoopbackToggle.node.on(
          Toggle.EventType.TOGGLE, this.onEnableLoopbackToggleChanged, this);
    }
    if(this.SceneToggleGroup) {
      const toggles = this.SceneToggleGroup.getComponentsInChildren(Toggle);
      for (const toggle of toggles) {
        toggle.node.on(Toggle.EventType.TOGGLE, this.onSceneChanged, this);
      }
    }
    if(this.AudioRoleToggleGroup) {
      const toggles = this.AudioRoleToggleGroup.getComponentsInChildren(Toggle);
      for (const toggle of toggles) {
        toggle.node.on(Toggle.EventType.TOGGLE, this.onAudioRoleChanged, this);
      }
    }
    if(this.RoomTypeToggleGroup) {
      const toggles = this.RoomTypeToggleGroup.getComponentsInChildren(Toggle);
      for (const toggle of toggles) {
        toggle.node.on(Toggle.EventType.TOGGLE, this.onRoomTypeChanged, this);
      }
    }
  }

  private uninitEventHandlers() {
    if (this.InitToggle) {
      this.InitToggle.node.off(Toggle.EventType.TOGGLE, this.onInitToggleChanged, this);
    }
    if (this.EnterRoomToggle) {
      this.EnterRoomToggle.node.off(Toggle.EventType.TOGGLE, this.onEnterRoomToggleChanged, this);
    }
    if (this.EnableMicToggle) {
      this.EnableMicToggle.node.off(Toggle.EventType.TOGGLE, this.onEnableMicToggleChanged, this);
    }
    if (this.EnableSpeakToggle) {
      this.EnableSpeakToggle.node.off(
          Toggle.EventType.TOGGLE, this.onEnableSpeakToggleChanged, this);
    }
    if (this.EnableLoopbackToggle) {
      this.EnableLoopbackToggle.node.off(
          Toggle.EventType.TOGGLE, this.onEnableLoopbackToggleChanged, this);
    }
    if(this.SceneToggleGroup) {
      const toggles = this.SceneToggleGroup.getComponentsInChildren(Toggle);
      for (const toggle of toggles) {
        toggle.node.off(Toggle.EventType.TOGGLE, this.onSceneChanged, this);
      }
    }
    if(this.AudioRoleToggleGroup) {
      const toggles = this.AudioRoleToggleGroup.getComponentsInChildren(Toggle);
      for (const toggle of toggles) {
        toggle.node.off(Toggle.EventType.TOGGLE, this.onAudioRoleChanged, this);
      }
    }
    if(this.RoomTypeToggleGroup) {
      const toggles = this.RoomTypeToggleGroup.getComponentsInChildren(Toggle);
      for (const toggle of toggles) {
        toggle.node.off(Toggle.EventType.TOGGLE, this.onRoomTypeChanged, this);
      }
    }
  }

  // ToggleContainerComponent事件处理函数
  private onSceneChanged(toggle: Toggle) {
    this.printApiResult(`Scene changed to: ${toggle.isChecked}`);
  }

  private onAudioRoleChanged(toggle: Toggle) {
    this.printApiResult(`AudioRole changed to: ${toggle.isChecked}`);
  }

  private onRoomTypeChanged(toggle: Toggle) {
    this.printApiResult(`RoomType changed to: ${toggle.isChecked}`);
  }

  private onSceneChanged(toggle: Toggle) {
    if (toggle.isChecked) { 
      if(toggle.node.name === 'Toggle1' ) {
        this.tmgContext.SetScene(ITMG_APP_SCENE.ITMG_APP_SCENE_RTC);
      } else {
        this.tmgContext.SetScene(ITMG_APP_SCENE.ITMG_APP_SCENE_LIVE);
      }
    }
  }

  private onAudioRoleChanged(toggle: Toggle) {
    if (toggle.isChecked) { 
      if(toggle.node.name === 'Toggle1' ) {
        this.tmgContext.SetAudioRole(ITMG_AUDIO_MEMBER_ROLE.ITMG_AUDIO_MEMBER_ROLE_ANCHOR);
      } else {
        this.tmgContext.SetAudioRole(ITMG_AUDIO_MEMBER_ROLE.ITMG_AUDIO_MEMBER_ROLE_AUDIENCE);
      }
    }
  }

  private onRoomTypeChanged(toggle: Toggle) {
    if (toggle.isChecked) { 
      if(toggle.node.name === 'Toggle1' ) {
        this.tmgContext.GetRoom().ChangeRoomType(ITMG_ROOM_TYPE.ITMG_ROOM_TYPE_FLUENCY);
      } else if(toggle.node.name === 'Toggle2'){
        this.tmgContext.GetRoom().ChangeRoomType(ITMG_ROOM_TYPE.ITMG_ROOM_TYPE_STANDARD);
      } else{
        this.tmgContext.GetRoom().ChangeRoomType(ITMG_ROOM_TYPE.ITMG_ROOM_TYPE_HIGHQUALITY);
      }
    }
  }

  // Toggle事件处理函数
  private onInitToggleChanged(toggle: Toggle) {
    this.printApiResult(`InitToggle changed to: ${toggle.isChecked}`);
    if (toggle.isChecked) {
      let ret = this.tmgContext.Init(this.AppidEditBox.string, this.UserIdEditBox.string);

      let authBuffer = GetAuthBuffer(
          Number(this.AppidEditBox.string), '', this.UserIdEditBox.string, this.KeyEditBox.string);
      this.tmgContext.GetPTT().ApplyPTTAuthbuffer(authBuffer);
      this.printApiResult('Init ret: ' + ret);
    } else {
      this.uninitEventHandlers();
      this.tmgContext.Uninit();
      this.EnterRoomToggle.isChecked = false;
      this.EnableMicToggle.isChecked = false;
      this.EnableSpeakToggle.isChecked = false;
      this.EnableLoopbackToggle.isChecked = false;
      this.setupEventHandlers();
    }
  }

  private onEnterRoomToggleChanged(toggle: Toggle) {
    this.printApiResult(`EnterRoomToggle changed to: ${toggle.isChecked}`);
    if (toggle.isChecked) {
      let roomId = this.RoomIdEditBox.string;
      let authBuffer = GetAuthBuffer(
          Number(this.AppidEditBox.string), roomId, this.UserIdEditBox.string,
          this.KeyEditBox.string);
      let roomType = this.getRoomType();
      this.printApiResult('roomType: ' + roomType);
      const scene = this.getScene();
      const role = this.getRole();
      this.tmgContext.SetScene(scene);
      this.tmgContext.SetAudioRole(role);
      let ret = this.tmgContext.EnterRoom(roomId, roomType, authBuffer);
      this.printApiResult('EnterRoom ret: ' + ret);
      if (ret != 0) {
        this.EnterRoomToggle.node.off(Toggle.EventType.TOGGLE, this.onEnterRoomToggleChanged, this);
        toggle.isChecked = false;
        this.EnterRoomToggle.node.on(Toggle.EventType.TOGGLE, this.onEnterRoomToggleChanged, this);
      }

    } else {
      this.tmgContext.ExitRoom();
    }
  }

  private onEnableMicToggleChanged(toggle: Toggle) {
    this.printApiResult(`EnableMicToggle changed to: ${toggle.isChecked}`);
    if (0 != this.tmgContext.GetAudioCtrl().EnableMic(toggle.isChecked)) {
      this.printApiResult('EnableMic failed');
      this.EnableMicToggle.node.off(Toggle.EventType.TOGGLE, this.onEnableMicToggleChanged, this);
      toggle.isChecked = !toggle.isChecked;
      this.EnableMicToggle.node.on(Toggle.EventType.TOGGLE, this.onEnableMicToggleChanged, this);
    }
  }

  private onEnableSpeakToggleChanged(toggle: Toggle) {
    this.printApiResult(`EnableSpeakToggle changed to: ${toggle.isChecked}`);
    if (0 != this.tmgContext.GetAudioCtrl().EnableSpeaker(toggle.isChecked)) {
      this.printApiResult('EnableSpeaker failed');
      this.EnableSpeakToggle.node.off(
          Toggle.EventType.TOGGLE, this.onEnableSpeakToggleChanged, this);
      toggle.isChecked = !toggle.isChecked;
      this.EnableSpeakToggle.node.on(
          Toggle.EventType.TOGGLE, this.onEnableSpeakToggleChanged, this);
    }
  }

  private onEnableLoopbackToggleChanged(toggle: Toggle) {
    this.printApiResult(`EnableLoopbackToggle changed to: ${toggle.isChecked}`);
    if (0 != this.tmgContext.GetAudioCtrl().EnableLoopBack(toggle.isChecked)) {
      this.printApiResult('EnableLoopBack failed');
      this.EnableLoopbackToggle.node.off(
          Toggle.EventType.TOGGLE, this.onEnableLoopbackToggleChanged, this);
      toggle.isChecked = !toggle.isChecked;
      this.EnableLoopbackToggle.node.on(
          Toggle.EventType.TOGGLE, this.onEnableLoopbackToggleChanged, this);
    }
  }

  getRoomType() {
    let roomType = 1;
    const toggles = this.RoomTypeToggleGroup.getComponentsInChildren(Toggle);
    for (const toggle of toggles) {
      if (toggle.isChecked) {
        roomType = parseInt(toggle.node.name.replace('Toggle', ''));
        break;
      }
    }
    return roomType;
  }

  getScene() {
    let scene = ITMG_APP_SCENE.ITMG_APP_SCENE_RTC;
    const toggles = this.SceneToggleGroup.getComponentsInChildren(Toggle);
    for (const toggle of toggles) {
      if (toggle.isChecked) {
        const toggleName = toggle.node.name.replace('Toggle', '');
        if (toggleName === '1') {
          scene = ITMG_APP_SCENE.ITMG_APP_SCENE_RTC;
        } else if (toggleName === '2') {
          scene = ITMG_APP_SCENE.ITMG_APP_SCENE_LIVE;
        }
        break;
      }
    }
    return scene;
  }

  getRole() {
    let role = ITMG_AUDIO_MEMBER_ROLE.ITMG_AUDIO_MEMBER_ROLE_ANCHOR;
    const toggles = this.AudioRoleToggleGroup.getComponentsInChildren(Toggle);
    for (const toggle of toggles) {
      if (toggle.isChecked) {
        const toggleName = toggle.node.name.replace('Toggle', '');
        if (toggleName === '2') {
          role = ITMG_AUDIO_MEMBER_ROLE.ITMG_AUDIO_MEMBER_ROLE_AUDIENCE;
        } else if (toggleName === '1') {
          role = ITMG_AUDIO_MEMBER_ROLE.ITMG_AUDIO_MEMBER_ROLE_ANCHOR;
        }
        break;
      }
    }
    return role;
  }

  addAPITestButton() {
    const TMGContextFuncs = this.apiList['TMGContext'];
    if (TMGContextFuncs) {
      this.addRichText('TMGContext 模块接口');
      for (let i = 0; i < TMGContextFuncs.length; i++) {
        this.addButtons(TMGContextFuncs[i]);
      }
    }

    const TMGAudioCtrlFuncs = this.apiList['TMGAudioCtrl'];
    if (TMGAudioCtrlFuncs) {
      this.addRichText('TMGAudioCtrl 模块接口');
      for (let i = 0; i < TMGAudioCtrlFuncs.length; i++) {
        this.addButtons(TMGAudioCtrlFuncs[i]);
      }
    }

    const TMGAudioEffectCtrlFuncs = this.apiList['TMGAudioEffectCtrl'];
    if (TMGAudioEffectCtrlFuncs) {
      this.addRichText('TMGAudioEffectCtrl 模块接口');
      for (let i = 0; i < TMGAudioEffectCtrlFuncs.length; i++) {
        this.addButtons(TMGAudioEffectCtrlFuncs[i]);
      }
    }

    const TMGRoomFuncs = this.apiList['TMGRoom'];
    if (TMGRoomFuncs) {
      this.addRichText('TMGRoom 模块接口');
      for (let i = 0; i < TMGRoomFuncs.length; i++) {
        this.addButtons(TMGRoomFuncs[i]);
      }
    }

    const PTTFuncs = this.apiList['PTT'];
    if (PTTFuncs) {
      this.addRichText('PTT 模块接口');
      for (let i = 0; i < PTTFuncs.length; i++) {
        this.addButtons(PTTFuncs[i]);
      }
    }
    // }
  }

  addRichText(text: string) {
    const richTextNode = instantiate(this.richTextPrefab);
    const richText = richTextNode.getComponent(RichText);
    if (richText) {
      richText.string = `<color=#000000>${text}</color>`;
      // richText.string = text;
      richText.fontSize = 12;    // Larger font size
      richText.lineHeight = 20;  // Increased line height
      // richText.horizontalAlign = Label.HorizontalAlign.LEFT;  // Left-align text
      richText.width = 300;
      richText.height = 35;
      if (this.apiSeq == 0) {
        richText.node.setPosition(-10, -35);
      } else {
        richText.node.setPosition(-10, -35 + this.apiSeq * -35);
      }
    }
    this.apiContent.addChild(richTextNode);
    this.apiSeq++;
  }


  addButtons(apiFunc: ApiFuncObj) {
    const buttonNode = instantiate(this.buttonPrefab);
    const button = buttonNode.getComponent(Button);
    buttonNode.width = 300;
    buttonNode.height = 35;

    if (this.apiSeq == 0) {
      button.node.setPosition(-10, -35);
    } else {
      button.node.setPosition(-10, -35 + this.apiSeq * -35);
    }

    const label = buttonNode.getChildByName('Label');
    if (label) {
      const labelComponent = label.getComponent(Label);
      if (labelComponent) {
        const fullText = apiFunc.funcName + '-' + apiFunc.funcDescription;
        const maxBytesPerLine = 32;
        let resultLines = [];
        let currentLine = '';

        for (let i = 0; i < fullText.length; i++) {
          currentLine += fullText[i];
          if (currentLine.length >= maxBytesPerLine) {
            resultLines.push(currentLine);
            currentLine = '';
          }
        }

        if (currentLine.length > 0) {
          resultLines.push(currentLine);
        }
        labelComponent.string = resultLines.join('\n');
        labelComponent.fontSize = 12;
        labelComponent.lineHeight = 20;
        labelComponent.horizontalAlign = Label.HorizontalAlign.LEFT;
        label.width = 300;
        label.height = 35;
        label.setPosition(13, 0);
      }
    }

    button.node.on(Button.EventType.CLICK, () => {
      apiFunc.handleClickName;
      this.invokeInstanceFunction(apiFunc.handleClickName, this);
    });
    this.apiContent.addChild(buttonNode);
    this.apiSeq++;
  }

  private invokeInstanceFunction(functionName: string, instance: any): void {
    if (typeof instance[functionName] === 'function') {
      instance[functionName]();
    } else {
      // this.printApiResult(`function ${functionName} not found`);
    }
  }


  GetMicStateClick() {
    let ret = this.tmgContext.GetAudioCtrl().GetMicState();
    this.printApiResult('GetMicState ret: ' + ret);
  }
  GetSpeakerStateClick() {
    let ret = this.tmgContext.GetAudioCtrl().GetSpeakerState();
    this.printApiResult('GetSpeakerState ret: ' + ret);
  }

  EnableAudioCaptureDeviceTrueClick() {
    const ret = this.tmgContext.GetAudioCtrl().EnableAudioCaptureDevice(true);
    this.printApiResult(`EnableAudioCaptureDevice true result: ${ret}`);
  }

  EnableAudioCaptureDeviceFalseClick() {
    const ret = this.tmgContext.GetAudioCtrl().EnableAudioCaptureDevice(false);
    this.printApiResult(`EnableAudioCaptureDevice false result: ${ret}`);
  }

  IsAudioCaptureDeviceEnabledClick() {
    const ret = this.tmgContext.GetAudioCtrl().IsAudioCaptureDeviceEnabled();
    this.printApiResult(`IsAudioCaptureDeviceEnabled result: ${ret}`);
  }

  EnableAudioPlayDeviceTrueClick() {
    const ret = this.tmgContext.GetAudioCtrl().EnableAudioPlayDevice(true);
    this.printApiResult(`EnableAudioPlayDeviceTrueClick result: ${ret}`);
  }

  EnableAudioPlayDeviceFalseClick() {
    const ret = this.tmgContext.GetAudioCtrl().EnableAudioPlayDevice(false);
    this.printApiResult(`EnableAudioPlayDeviceFalseClick result: ${ret}`);
  }

  IsAudioPlayDeviceEnabledClick() {
    const ret = this.tmgContext.GetAudioCtrl().IsAudioPlayDeviceEnabled();
    this.printApiResult(`IsAudioPlayDeviceEnabled result: ${ret}`);
  }

  // 打开关闭音频上行
  EnableAudioSendClick() {
    const ret = this.tmgContext.GetAudioCtrl().EnableAudioSend(true);
    this.printApiResult(`EnableAudioSend result: ${ret}`);
  }

  EnableAudioSendFalseClick() {
    const ret = this.tmgContext.GetAudioCtrl().EnableAudioSend(false);
    this.printApiResult(`EnableAudioSend false result: ${ret}`);
  }

  // 获取音频上行状态
  IsAudioSendEnabledClick() {
    const ret = this.tmgContext.GetAudioCtrl().IsAudioSendEnabled();
    this.printApiResult(`IsAudioSendEnabled result: ${ret}`);
  }

  // 打开或关闭音频下行
  EnableAudioRecvTrueClick() {
    const ret = this.tmgContext.GetAudioCtrl().EnableAudioRecv(true);
    this.printApiResult(`EnableAudioRecv true result: ${ret}`);
  }

  EnableAudioRecvFalseClick() {
    const ret = this.tmgContext.GetAudioCtrl().EnableAudioRecv(false);
    this.printApiResult(`EnableAudioRecv false result: ${ret}`);
  }

  // 获取音频下行状态
  IsAudioRecvEnabledClick() {
    const ret = this.tmgContext.GetAudioCtrl().IsAudioRecvEnabled();
    this.printApiResult(`IsAudioRecvEnabled result: ${ret}`);
  }

  // 设置麦克风音量的增益
  SetMicVolumeClick() {
    const ret = this.tmgContext.GetAudioCtrl().SetMicVolume(20);
    this.printApiResult(`SetMicVolume 20 result: ${ret}`);
  }

  // 获取麦克风音量的增益
  GetMicVolumeClick() {
    const ret = this.tmgContext.GetAudioCtrl().GetMicVolume();
    this.printApiResult(`GetMicVolume result: ${ret}`);
  }

  // 设置扬声器音量的增益
  SetSpeakerVolumeClick() {
    const ret = this.tmgContext.GetAudioCtrl().SetSpeakerVolume(20);
    this.printApiResult(`SetSpeakerVolume 20 result: ${ret}`);
  }

  // 获取扬声器音量的增益
  GetSpeakerVolumeClick() {
    const ret = this.tmgContext.GetAudioCtrl().GetSpeakerVolume();
    this.printApiResult(`GetSpeakerVolume result: ${ret}`);
  }

  // 动态设置房间内某成员音量增益
  SetSpeakerVolumeByUserIDClick() {
    const ret = this.tmgContext.GetAudioCtrl().SetSpeakerVolumeByUserID('653', 20);
    this.printApiResult(`SetSpeakerVolumeByUserID result: ${ret}`);
  }

  // 获取某成员音量增益
  GetSpeakerVolumeByUserIDClick() {
    const ret = this.tmgContext.GetAudioCtrl().GetSpeakerVolumeByUserID('653');
    this.printApiResult(`GetSpeakerVolumeByUserID result: ${ret}`);
  }

  // 禁言房间中某个用户
  AddAudioBlackListClick() {
    const ret = this.tmgContext.GetAudioCtrl().AddAudioBlackList('653');
    this.printApiResult(`AddAudioBlackList result: ${ret}`);
  }

  // 取消禁言房间中某个用户
  RemoveAudioBlackListClick() {
    const ret = this.tmgContext.GetAudioCtrl().RemoveAudioBlackList('653');
    this.printApiResult(`RemoveAudioBlackList result: ${ret}`);
  }

  // 查询某个用户是否被禁言
  IsUserIDInAudioBlackListClick() {
    const ret = this.tmgContext.GetAudioCtrl().IsUserIDInAudioBlackList('653');
    this.printApiResult(`IsUserIDInAudioBlackList result: ${ret}`);
  }

  // 开启或关闭3D音效
  EnableSpatializerTrueClick() {
    const ret = this.tmgContext.GetAudioCtrl().EnableSpatializer(true);
    this.printApiResult(`EnableSpatializerTrueClick result: ${ret}`);
  }

  EnableSpatializerFalseClick() {
    const ret = this.tmgContext.GetAudioCtrl().EnableSpatializer(false);
    this.printApiResult(`EnableSpatializerFalseClick result: ${ret}`);
  }

  // 获取当前3D音效状态
  IsEnableSpatializerClick() {
    const ret = this.tmgContext.GetAudioCtrl().IsEnableSpatializer();
    this.printApiResult(`IsEnableSpatializer result: ${ret}`);
  }

  // 开启音量回调
  TrackingVolumeClick() {
    const ret = this.tmgContext.GetAudioCtrl().TrackingVolume(2);
    this.printApiResult(`TrackingVolume 2s result: ${ret}`);
  }

  // 停止音量回调
  StopTrackingVolumeClick() {
    const ret = this.tmgContext.GetAudioCtrl().StopTrackingVolume();
    this.printApiResult(`StopTrackingVolume result: ${ret}`);
  }

  // 获取实时麦克风音量
  GetMicLevelClick() {
    const ret = this.tmgContext.GetAudioCtrl().GetMicLevel();
    this.printApiResult(`GetMicLevel result: ${ret}`);
  }

  // 获取实时扬声器音量
  GetSpeakerLevelClick() {
    const ret = this.tmgContext.GetAudioCtrl().GetSpeakerLevel();
    this.printApiResult(`GetSpeakerLevel result: ${ret}`);
  }

  // 获取音频上行实时音量
  GetSendStreamLevelClick() {
    const ret = this.tmgContext.GetAudioCtrl().GetSendStreamLevel();
    this.printApiResult(`GetSendStreamLevel result: ${ret}`);
  }

  // 获取音频下行实时音量
  GetRecvStreamLevelClick() {
    const ret = this.tmgContext.GetAudioCtrl().GetRecvStreamLevel('653');
    this.printApiResult(`GetRecvStreamLevel result: ${ret}`);
  }

  // 开始麦克风测试（仅桌面端有效）
  StartMicDeviceTestClick() {
    const ret = this.tmgContext.GetAudioCtrl().StartMicDeviceTest(300);
    this.printApiResult(`StartMicDeviceTest result: ${ret}`);
  }

  // 停止麦克风测试（仅桌面端有效）
  StopMicDeviceTestClick() {
    const ret = this.tmgContext.GetAudioCtrl().StopMicDeviceTest();
    this.printApiResult(`StopMicDeviceTest result: ${ret}`);
  }

  // 开始扬声器测试（仅桌面端有效）
  StartSpeakerDeviceTestClick() {
    let absolutePath =
        'https://gmeh5-test-1256590279.cos.ap-guangzhou.myqcloud.com/TestAudio/8.mp3';
    const ret = this.tmgContext.GetAudioCtrl().StartSpeakerDeviceTest(absolutePath);

    console.log(absolutePath);  // 输出文件的路径
    this.printApiResult(`StartSpeakerDeviceTest result: ${ret}`);
  }

  // 停止扬声器测试（仅桌面端有效）
  StopSpeakerDeviceTestClick() {
    const ret = this.tmgContext.GetAudioCtrl().StopSpeakerDeviceTest();
    this.printApiResult(`StopSpeakerDeviceTest result: ${ret}`);
  }

  // 获取麦克风设备数量（仅桌面端有效）
  GetMicListCountClick() {
    const ret = this.tmgContext.GetAudioCtrl().GetMicListCount();
    this.printApiResult(`GetMicListCount result: ${ret}`);
  }

  // 获取麦克风设备列表（仅桌面端有效）
  GetMicListClick() {
    let num = this.tmgContext.GetAudioCtrl().GetMicListCount();
    const micInfoArry: TMGAudioDeviceInfo[] = this.tmgContext.GetAudioCtrl().GetMicList(num);
    for (const item of micInfoArry) {
      this.printApiResult(`GetMicList result: ${item.device_id},  ${item.device_name}`);
    }
    // this.printApiResult(`GetMicList result: ${ret}`);
  }

  // 选择麦克风设备（仅桌面端有效）
  SelectMicClick() {
    let num = this.tmgContext.GetAudioCtrl().GetMicListCount();
    const micInfoArry: TMGAudioDeviceInfo[] = this.tmgContext.GetAudioCtrl().GetMicList(num);
    if (num == 0) {
      this.printApiResult(`SelectMic err no mic`);
      return;
    }
    const ret = this.tmgContext.GetAudioCtrl().SelectMic(micInfoArry[num - 1].device_id);
    this.printApiResult(`SelectMic ${micInfoArry[num - 1].device_id}, result: ${ret}`);
  }

  // 获取当前使用的麦克风设备（仅桌面端有效）
  GetCurrentMicClick() {
    let micInfo = this.tmgContext.GetAudioCtrl().GetCurrentMic();
    this.printApiResult(`GetCurrentMic result: ${micInfo.device_id},  ${micInfo.device_name}`);
  }

  // 获取扬声器设备数量（仅桌面端有效）
  GetSpeakerListCountClick() {
    const ret = this.tmgContext.GetAudioCtrl().GetSpeakerListCount();
    this.printApiResult(`GetSpeakerListCount result: ${ret}`);
  }

  // 获取扬声器设备列表（仅桌面端有效）
  GetSpeakerListClick() {
    let num = this.tmgContext.GetAudioCtrl().GetSpeakerListCount();
    const micInfoArry: TMGAudioDeviceInfo[] = this.tmgContext.GetAudioCtrl().GetSpeakerList(num);
    for (const item of micInfoArry) {
      this.printApiResult(`GetSpeakerListClick result: ${item.device_id},  ${item.device_name}`);
    }


    // const count = this.tmgContext.GetAudioCtrl().GetSpeakerListCount();
    // const ret = this.tmgContext.GetAudioCtrl().GetSpeakerList(count);
    // this.printApiResult(`GetSpeakerList result: ${ret}`);
  }

  // 选择扬声器设备（仅桌面端有效）
  SelectSpeakerClick() {
    let num = this.tmgContext.GetAudioCtrl().GetMicListCount();
    const micInfoArry: TMGAudioDeviceInfo[] = this.tmgContext.GetAudioCtrl().GetSpeakerList(num);
    if (num == 0) {
      this.printApiResult(`SelectMic err no mic`);
      return;
    }

    const ret = this.tmgContext.GetAudioCtrl().SelectSpeaker(micInfoArry[num - 1].device_id);
    this.printApiResult(`SelectSpeaker ${micInfoArry[num - 1].device_id}, result: ${ret}`);
  }

  // 获取当前使用的扬声器设备（仅桌面端有效）
  GetCurrentSpeakerClick() {
    const spkInfo = this.tmgContext.GetAudioCtrl().GetCurrentSpeaker();
    this.printApiResult(`GetCurrentSpeaker result: ${spkInfo.device_id},  ${spkInfo.device_name}`);
  }

  // 设置音频路由
  SetAudioRouteSPEAKERClick() {
    const ret = this.tmgContext.GetAudioCtrl().SetAudioRoute(0);
    this.printApiResult(`SetAudioRouteSPEAKERClick result: ${ret}`);
  }

  SetAudioRouteEARPIECEClick() {
    const ret = this.tmgContext.GetAudioCtrl().SetAudioRoute(1);
    this.printApiResult(`SetAudioRouteEARPIECEClick result: ${ret}`);
  }

  // ================= TMGAudioEffectCtrl 模块 =================

  // 开始播放背景音乐
  StartPlayMusicClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().StartPlayMusic(
        1, 'https://gmeh5-test-1256590279.cos.ap-guangzhou.myqcloud.com/TestAudio/8.mp3', 1);
    this.printApiResult(`StartPlayMusic result: ${ret}`);
  }

  // 停止播放背景音乐
  StopPlayMusicClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().StopPlayMusic(1);
    this.printApiResult(`StopPlayMusic result: ${ret}`);
  }

  // 暂停播放背景音乐
  PausePlayMusicClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().PausePlayMusic(1);
    this.printApiResult(`PausePlayMusic result: ${ret}`);
  }

  // 恢复播放背景音乐
  ResumePlayMusicClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().ResumePlayMusic(1);
    this.printApiResult(`ResumePlayMusic result: ${ret}`);
  }

  // 背景音乐是否播放结束
  IsMusicPlayEndClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().IsMusicPlayEnd(1);
    this.printApiResult(`IsMusicPlayEnd result: ${ret}`);
  }

  // 设置所有背景音乐的本地和远端音量
  SetAllMusicVolumeClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().SetAllMusicVolume(20);
    this.printApiResult(`SetAllMusicVolume result: ${ret}`);
  }

  // ================= TMGAudioEffectCtrl 音量控制 =================

  // 设置某一首背景音乐的远端音量大小-10
  SetMusicPublishVolume10Click() {
    const ret = this.tmgContext.GetAudioEffectCtrl().SetMusicPublishVolume(1, 10);
    this.printApiResult(`SetMusicPublishVolumeClick(10) result: ${ret}`);
  }

  // 设置某一首背景音乐的远端音量大小-100
  SetMusicPublishVolume100Click() {
    const ret = this.tmgContext.GetAudioEffectCtrl().SetMusicPublishVolume(1, 100);
    this.printApiResult(`SetMusicPublishVolume(100) result: ${ret}`);
  }

  // 获取某一首背景音乐的远端音量大小
  GetMusicPublishVolumeClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().GetMusicPublishVolume(1);
    this.printApiResult(`GetMusicPublishVolume result: ${ret}`);
  }

  // 控制某一首背景音乐的本地音量-0
  SetMusicPlayoutVolume10Click() {
    const ret = this.tmgContext.GetAudioEffectCtrl().SetMusicPlayoutVolume(1, 10);
    this.printApiResult(`SetMusicPlayoutVolume(10) result: ${ret}`);
  }

  // 控制某一首背景音乐的本地音量-100
  SetMusicPlayoutVolume100Click() {
    const ret = this.tmgContext.GetAudioEffectCtrl().SetMusicPlayoutVolume(1, 100);
    this.printApiResult(`SetMusicPlayoutVolume(100) result: ${ret}`);
  }

  // 获取某一首背景音乐的本地音量大小
  GetMusicPlayoutVolumeClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().GetMusicPlayoutVolume(1);
    this.printApiResult(`GetMusicPlayoutVolume result: ${ret}`);
  }

  // ================= TMGAudioEffectCtrl 音乐进度控制 =================

  // 调整背景音乐的音调高低-1
  SetMusicPitch1Click() {
    const ret = this.tmgContext.GetAudioEffectCtrl().SetMusicPitch(1, 1.0);
    this.printApiResult(`SetMusicPitch(1.0) result: ${ret}`);
  }

  // 调整背景音乐的音调高低--1
  SetMusicPitchClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().SetMusicPitch(1, -1.0);
    this.printApiResult(`SetMusicPitch(-1.0) result: ${ret}`);
  }

  // 获取背景音乐的总时长毫秒
  GetMusicDurationInMSClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().GetMusicDurationInMS(1);
    this.printApiResult(`GetMusicDurationInMS result: ${ret}`);
  }

  // 获取背景音乐的播放进度毫秒
  GetMusicCurrentPosInMSClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().GetMusicCurrentPosInMS(1);
    this.printApiResult(`GetMusicCurrentPosInMS result: ${ret}`);
  }

  // 设置背景音乐的播放进度毫秒-16000
  SeekMusicToPosInTimeClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().SeekMusicToPosInTime(1, 16000);
    this.printApiResult(`SeekMusicToPosInTime-16000 result: ${ret}`);
  }

  EnableMusicPublisClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().EnableMusicPublish(1, true);
    this.printApiResult(`EnableMusicPublisClick result: ${ret}`);
  }

  DisEnableMusicPublisClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().EnableMusicPublish(1, false);
    this.printApiResult(`DisEnableMusicPublisClick result: ${ret}`);
  }

  EnableMusicPlayoutClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().EnableMusicPlayout(1, true);
    this.printApiResult(`EnableMusicPlayoutClick result: ${ret}`);
  }

  DisEnableMusicPlayoutClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().EnableMusicPlayout(1, false);
    this.printApiResult(`DisEnableMusicPlayoutClick result: ${ret}`);
  }

  // 设置人声的变声特效
  SetVoiceTypeClick() {
    const ret =
        this.tmgContext.GetAudioEffectCtrl().SetVoiceType(ITMG_VOICE_TYPE.ITMG_VOICE_TYPE_LOLITA);
    this.printApiResult(`SetVoiceType result: ${ret}`);
  }

  SetVoiceTypeCloseClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().SetVoiceType(
        ITMG_VOICE_TYPE.ITMG_VOICE_TYPE_ORIGINAL_SOUND);
    this.printApiResult(`SetVoiceTypeClose result: ${ret}`);
  }

  // 设置人声的混响特效
  SetKaraokeTypeClick() {
    const ret =
        this.tmgContext.GetAudioEffectCtrl().SetKaraokeType(ITMG_KARAOKE_TYPE.ITMG_KARAOKE_TYPE_10);
    this.printApiResult(`SetKaraokeType result: ${ret}`);
  }

  SetKaraokeTypeCloseClick() {
    const ret =
        this.tmgContext.GetAudioEffectCtrl().SetKaraokeType(ITMG_KARAOKE_TYPE.ITMG_KARAOKE_TYPE_0);
    this.printApiResult(`SetKaraokeTypeClose result: ${ret}`);
  }

  // ================= TMGAudioEffectCtrl 音频录制 =================

  // 开始录制音频-ALL
  StartRecordALLClick() {
    let filePath = this.recordFilePath + 'record_all.wav';
    const ret = this.tmgContext.GetAudioEffectCtrl().StartRecord(
        filePath, ITMG_AUDIO_RECORDING_CONTENT.ITMG_AUDIO_RECORDING_CONTENT_ALL);
    this.printApiResult(`StartRecord(ALL) result: ${ret}`);
  }

  // 开始录制音频-Local
  StartRecordLocalClick() {
    let filePath = this.recordFilePath + 'record_local.wav';
    const ret = this.tmgContext.GetAudioEffectCtrl().StartRecord(
        filePath, ITMG_AUDIO_RECORDING_CONTENT.ITMG_AUDIO_RECORDING_CONTENT_LOCAL);
    this.printApiResult(`StartRecord(Local) result: ${ret}`);
  }

  // 开始录制音频-Remote
  StartRecordRemoteClick() {
    let filePath = this.recordFilePath + 'record_remote.wav';
    const ret = this.tmgContext.GetAudioEffectCtrl().StartRecord(
        filePath, ITMG_AUDIO_RECORDING_CONTENT.ITMG_AUDIO_RECORDING_CONTENT_REMOTE);
    this.printApiResult(`StartRecord(Remote) result: ${ret}`);
  }

  // 停止录制音频
  StopRecordClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().StopRecord();
    this.printApiResult(`StopRecord result: ${ret}`);
  }

  // 开启系统声音采集
  StartSystemAudioLoopbackClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().StartSystemAudioLoopback('');
    this.printApiResult(`StartSystemAudioLoopback result: ${ret}`);
  }

  // 停止系统声音采集
  StopSystemAudioLoopbackClick() {
    const ret = this.tmgContext.GetAudioEffectCtrl().StopSystemAudioLoopback();
    this.printApiResult(`StopSystemAudioLoopback result: ${ret}`);
  }

  // 设置系统声音的采集音量-10
  SetSystemAudioLoopbackVolume10Click() {
    const ret = this.tmgContext.GetAudioEffectCtrl().SetSystemAudioLoopbackVolume(10);
    this.printApiResult(`SetSystemAudioLoopbackVolume(10) result: ${ret}`);
  }

  // ================= TMGRoom 模块 =================

  // 获取语音房间ID
  GetRoomIDClick() {
    const ret = this.tmgContext.GetRoom().GetRoomID();
    this.printApiResult(`GetRoomID result: ${ret}`);
  }

  // 修改用户房间音频类型
  ChangeRoomTypeClick() {
    const roomType = this.getRoomType();
    const ret = this.tmgContext.GetRoom().ChangeRoomType(roomType);
    this.printApiResult(`ChangeRoomType result: ${ret}`);
  }

  // 获取用户房间音频类型
  GetRoomTypeClick() {
    const ret = this.tmgContext.GetRoom().GetRoomType();
    this.printApiResult(`GetRoomType result: ${ret}`);
  }

  // 开始跨房连麦通话
  StartRoomSharingClick() {
    const authBuffer = GetAuthBuffer(
        Number(this.AppidEditBox.string), '888', this.UserIdEditBox.string, this.KeyEditBox.string);
    const ret = this.tmgContext.GetRoom().StartRoomSharing('888', '653', authBuffer);
    this.printApiResult(`StartRoomSharing result: ${ret}`);
  }

  // 结束跨房连麦通话
  StopRoomSharingClick() {
    const ret = this.tmgContext.GetRoom().StopRoomSharing();
    this.printApiResult(`StopRoomSharing result: ${ret}`);
  }

  // 快速切换房间
  SwitchRoomClick() {
    const authBuffer = GetAuthBuffer(
        Number(this.AppidEditBox.string), '888', this.UserIdEditBox.string, this.KeyEditBox.string);
    const ret = this.tmgContext.GetRoom().SwitchRoom('888', authBuffer);
    this.printApiResult(`SwitchRoom result: ${ret}`);
  }

  private stringToUint8Array(str: string): Uint8Array {
    const buffer = new ArrayBuffer(str.length);
    const uint8Array = new Uint8Array(buffer);

    for (let i = 0; i < str.length; i++) {
      uint8Array[i] = str.charCodeAt(i);
    }

    return uint8Array;
  }

  // 发送自定义消息
  SendCustomDataClick() {
    let str = '测试1234567890end';
    const encoder = new TextEncoder();
    const uint8Array = encoder.encode(str);

    // 将 Uint8Array 转换为 ArrayBuffer
    const arrayBuffer = uint8Array.buffer;

    const ret = this.tmgContext.GetRoom().SendCustomData(arrayBuffer, -1);
    this.printApiResult(`SendCustomData result: ${ret}`);
  }

  // 停止发送自定义消息
  StopSendCustomDataClick() {
    const ret = this.tmgContext.GetRoom().StopSendCustomData();
    this.printApiResult(`StopSendCustomData result: ${ret}`);
  }

  // 设置接收语音距离范围
  UpdateAudioRecvRangeClick() {
    const ret = this.tmgContext.GetRoom().UpdateAudioRecvRange(1);
    this.printApiResult(`UpdateAudioRecvRange result: ${ret}`);
  }

  // 设置3D音效衰减距离
  UpdateSpatializerRecvRangeClick() {
    const ret = this.tmgContext.GetRoom().UpdateSpatializerRecvRange(1);
    this.printApiResult(`UpdateSpatializerRecvRange result: ${ret}`);
  }

  // 更新玩家声源方位及坐标
  UpdateSelfOrOtherPositionClick() {
    this.currentSceneNode.active = false;
    UpdatePostion.g_mySelfuserID = this.UserIdEditBox.string;

    this.updatePositionNode.active = true;
  }

  // // 更新远端用户空间坐标
  // UpdateOtherPositionClick() {
  //   // let floatArray = new Float32Array([1.0, 2.0, 3.0]);

  //   // // const position = [1.0, 0.0, 0.0];
  //   // const ret = this.tmgContext.GetRoom().UpdateOtherPosition('653', floatArray);
  //   // this.printApiResult(`UpdateOtherPosition result: ${ret}`);
  // }

  // 使用SEI通道发送自定义消息
  SendSEIMsgClick() {
    const str1 = '开始测试1234567890end';
    const ret = this.tmgContext.GetRoom().SendSEIMsg(str1, str1.length);
    this.printApiResult(`SendSEIMsg result: ${ret}`);
  }

  // ================= TMGContext 模块 =================

  // 设置接入点-DEFAULT_TEST
  SetRegionDEFAULT_TESTClick() {
    this.tmgContext.SetRegion('DEFAULT_TEST');
    this.printApiResult(`SetRegion DEFAULT_TEST`);
  }

  // 设置接入点-DEFAULT
  SetRegionDEFAULTClick() {
    this.tmgContext.SetRegion('DEFAULT');
    this.printApiResult(`SetRegion DEFAULT`);
  }

  // 设置范围语音模式
  SetRangeAudioModeClick() {
    const ret = this.tmgContext.SetRangeAudioMode(
        ITMG_RANGE_AUDIO_MODE.ITMG_RANGE_AUDIO_MODE_SND_TEAM_REC_TEAM);  // 1表示范围语音模式
    this.printApiResult(`SetRangeAudioMode result: ${ret}`);
  }

  // 设置范围语音的TeamID-2
  SetRangeAudioTeamID2Click() {
    const ret = this.tmgContext.SetRangeAudioTeamID(2);
    this.printApiResult(`SetRangeAudioTeamID(2) result: ${ret}`);
  }

  // 设置范围语音的TeamID-0
  SetRangeAudioTeamID0Click() {
    const ret = this.tmgContext.SetRangeAudioTeamID(0);
    this.printApiResult(`SetRangeAudioTeamID(0) result: ${ret}`);
  }

  // 是否已经在语音房间内
  IsRoomEnteredClick() {
    const ret = this.tmgContext.IsRoomEntered();
    this.printApiResult(`IsRoomEntered result: ${ret}`);
  }

  // 设置打印日志等级ERROR,ERROR
  SetLogLevelClick() {
    const ret = this.tmgContext.SetLogLevel(
        ITMG_LOG_LEVEL.ITMG_LOG_LEVEL_ERROR, ITMG_LOG_LEVEL.ITMG_LOG_LEVEL_ERROR);
    this.printApiResult(`SetLogLevel result: ${ret}`);
  }

  // 设置日志文件保存路径
  SetLogPathClick() {
    let newLogPath: String;
    if(cc.sys.os === cc.sys.OS_ANDROID) {
      const path = this.tmgContext.GetLogPath();
      let index = path.indexOf("com.tencent.gme.demo.cocosCreator");
      if (index != -1) {
        newLogPath = path.substring(0, index + "com.tencent.gme.demo.cocosCreator".length) + "/gmelog";
      } else {
        newLogPath = jsb.fileUtils.getWritablePath() + 'gmelog';
      }
    } else {
      newLogPath = jsb.fileUtils.getWritablePath() + 'gmelog';
    }
    
    const ret = this.tmgContext.SetLogPath(newLogPath);
    this.printApiResult(`SetLogPath path: ${newLogPath}`);
  }

  // 获取日志文件保存路径
  GetLogPathClick() {
    const ret = this.tmgContext.GetLogPath();
    this.printApiResult(`GetLogPath result: ${ret}`);
  }

  // 获取GME SDK版本
  GetSDKVersionClick() {
    const ret = this.tmgContext.GetSDKVersion();
    this.printApiResult(`GetSDKVersion result: ${ret}`);
  }

  // 设置App版本号
  SetAppVersionClick() {
    this.tmgContext.SetAppVersion('gme cocoscreator3.0.3');
    this.printApiResult(`SetAppVersion`);
  }

  // 设置最大混音路数5
  SetRecvMixStreamCountClick() {
    const ret = this.tmgContext.SetRecvMixStreamCount(5);
    this.printApiResult(`SetRecvMixStreamCount result: ${ret}`);
  }

  // 设置高级功能参数
  SetAdvanceParamsClick() {
    const ret = this.tmgContext.SetAdvanceParams('DisableEncryptLog', '1');
    this.printApiResult(`SetAdvanceParams DisableEncryptLog : 1, result: ${ret}`);
  }

  // 获取高级功能参数值
  GetAdvanceParamsClick() {
    const ret = this.tmgContext.GetAdvanceParams('DisableEncryptLog');
    this.printApiResult(`GetAdvanceParams result: ${ret}`);
  }

  // 查询麦克风权限
  CheckMicPermissionClick() {
    const ret = this.tmgContext.CheckMicPermission();
    this.printApiResult(`CheckMicPermission result: ${ret}`);
  }

  ClosePrintfHighFrequencyLogClick() {
    this.isPrintfHighFrequencyLog = false;
    this.printApiResult(`ClosePrintfHighFrequencyLog`);
  }

  OpenPrintfHighFrequencyLogClick() {
    this.isPrintfHighFrequencyLog = true;
    this.printApiResult(`OpenPrintfHighFrequencyLog`);
  }




  // ================= PTT 模块 =================

  // 限制最大语音信息时长
  SetMaxMessageLengthClick() {
    const ret = this.tmgContext.GetPTT().SetMaxMessageLength(180000);
    this.printApiResult(`SetMaxMessageLength result: ${ret}`);
  }

  // 启动录音
  StartRecordingClick() {
    const filePath = this.recordFilePath + 'ptt_record.ogg';
    const ret = this.tmgContext.GetPTT().StartRecording(filePath);
    this.printApiResult(`StartRecording result: ${ret}`);
  }

  // 停止录音
  StopRecordingClick() {
    const ret = this.tmgContext.GetPTT().StopRecording();
    this.printApiResult(`StopRecording result: ${ret}`);
  }

  // 取消录音
  CancelRecordingClick() {
    const ret = this.tmgContext.GetPTT().CancelRecording();
    this.printApiResult(`CancelRecording result: ${ret}`);
  }

  // 上传语音文件
  UploadRecordedFileClick() {
    const ret = this.tmgContext.GetPTT().UploadRecordedFile(this.pttFilePath);
    this.printApiResult(`UploadRecordedFile result: ${ret}`);
  }

  // 下载语音文件
  DownloadRecordedFileClick() {
    const fileID = 'test_file_id';
    const filePath = this.recordFilePath + 'ptt_download.ogg';
    const ret = this.tmgContext.GetPTT().DownloadRecordedFile(this.pttFileId, filePath);
    this.printApiResult(`DownloadRecordedFile result: ${ret}`);
  }

  // 播放语音
  PlayRecordedFileClick() {
    const ret = this.tmgContext.GetPTT().PlayRecordedFile(this.pttFilePath);
    this.printApiResult(`PlayRecordedFile result: ${ret}`);
  }

  // 播放语音-萝莉音
  PlayRecordedFileVoiceTtpeClick() {
    const filePath = this.recordFilePath + 'ptt_record.ogg';
    const ret = this.tmgContext.GetPTT().PlayRecordedFile(
        this.pttFilePath, ITMG_VOICE_TYPE.ITMG_VOICE_TYPE_LOLITA);
    this.printApiResult(`PlayRecordedFile(萝莉音) result: ${ret}`);
  }

  // 停止播放语音
  StopPlayFileClick() {
    const ret = this.tmgContext.GetPTT().StopPlayFile();
    this.printApiResult(`StopPlayFile result: ${ret}`);
  }

  // 语音转文本
  SpeechToTextClick() {
    const ret = this.tmgContext.GetPTT().SpeechToText(this.pttFileId, 'cmn-Hans-CN', 'cmn-Hans-CN');
    this.printApiResult(`SpeechToText result: ${ret}`);
  }

  // 文本翻译
  TranslateTextClick() {
    const ret = this.tmgContext.GetPTT().TranslateText(this.pttText, 'cmn-Hans-CN', 'en-US');
    this.printApiResult(`TranslateText result: ${ret}`);
  }

  // 获取语音文件大小
  GetFileSizeClick() {
    const ret = this.tmgContext.GetPTT().GetFileSize(this.pttFilePath);
    this.printApiResult(`GetFileSize result: ${ret}`);
  }

  // 获取语音文件时长
  GetVoiceFileDurationClick() {
    const ret = this.tmgContext.GetPTT().GetVoiceFileDuration(this.pttFilePath);
    this.printApiResult(`GetVoiceFileDuration result: ${ret}`);
  }

  // 启动流式语音识别
  StartRecordingWithStreamingRecognitionClick() {
    const filePath = this.recordFilePath + 'ptt_stream.ogg';
    const ret = this.tmgContext.GetPTT().StartRecordingWithStreamingRecognition(
        filePath, 'cmn-Hans-CN', 'cmn-Hans-CN');
    this.printApiResult(`StartRecordingWithStreamingRecognition result: ${ret}`);
  }

  // 设置PTT功能源语言
  SetPTTSourceLanguageClick() {
    const ret = this.tmgContext.GetPTT().SetPTTSourceLanguage('en-US');
    this.printApiResult(`SetPTTSourceLanguage result: ${ret}`);
  }

  // 文本转语音
  TextToSpeechClick() {
    const ret = this.tmgContext.GetPTT().TextToSpeech(
        1, this.pttText, 'cmn-CN-Standard-A', 'cmn-Hans-CN', 1);
    this.printApiResult(`TextToSpeech result: ${ret}`);
  }
}