Harmony SoundPool 的初始化 加载资源 播放

typescript 复制代码
private player?: media.SoundPool;

async initAndLoad() {
  await this.initSoundPool();
  await this.loadSounds();
  this.ready = true;
}

async release() {
  await this.player?.release();
  this.ready = false;
}

async initSoundPool() {
  this.player = await media.createSoundPool(1, {
    usage: audio.StreamUsage.STREAM_USAGE_GAME,
    rendererFlags: 1
  },)
}

async loadSounds() {
  this.soundIds = [];
  for (let i = 0; i < this.audioOptions.length; i++) {
    let audio: AudioOption = this.audioOptions[i];
    let id = await this.loadSoundId(audio.src);
    this.soundIds.push(id);
  }
}

async loadSoundId(rawFile: string): Promise<number> {
  let res = await getContext().resourceManager.getRawFd(rawFile);
  return new Promise<number>((resolve, reject) => {
    this.player!.load(res.fd, res.offset, res.length, (error, id: number) => {
      if (!error) {
        resolve(id);
      } else {
        reject(error);
      }
    })
  });
}

tick(): void {
  if (!this.ready) {
    return;
  }
  this.player?.play(this.soundIds[this.activeAudioIndex]);
  this.counter++;
}
相关推荐
SZYSK3 小时前
鸿蒙人脸识别算法放在终端里:和外挂授权 SDK 差在排障路径
物联网·算法·华为·harmonyos
贾伟康4 小时前
【健康菜谱助手|06】HarmonyOS ArkTS 烹饪计时器实战:处理倒计时、暂停、恢复和到期反馈
软件测试·移动开发·harmonyos·arkts·arkui
贾伟康7 小时前
【健康菜谱助手|05】HarmonyOS ArkTS 购物清单实战:去重食材并同步勾选、数量与清空动作
软件测试·移动开发·harmonyos·arkts·arkui
特立独行的猫a8 小时前
仓颉语言cj-tauri 跨端开发框架实战:给鸿蒙侧加一个「读设备电量」的原生能力
ui·harmonyos·tauri·1024程序员节·仓颉·鸿蒙pc
贾伟康18 小时前
【健康菜谱助手|01】HarmonyOS ArkTS 菜谱详情页实战:组织食材、营养、步骤和收藏状态
软件测试·移动开发·harmonyos·arkts·arkui
一目Leizi1 天前
折叠屏适配踩坑实录:从“一展开就变形“到一套代码适配多种形态【鸿蒙心迹】
华为·harmonyos
马剑威(威哥爱编程)1 天前
【HarmonyOS 7 小艺智能体实战】03:第一次建智能体——在小艺开放平台把骨架立起来
人工智能·华为·harmonyos
KevinChaos1 天前
HarmonyOS 7.0 端侧3DGS实验⑤:空洞、漂浮伪影与视角稳定
harmonyos
fellow991 天前
DSH Desktop - HarmonyOS Edition
harmonyos·openharmony·deepseek·deepseekharness