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++;
}
相关推荐
zhanshuo3 小时前
鸿蒙应用调试与测试实战全指南:高效定位问题,性能优化必备技巧+实用代码示例
harmonyos
万少7 小时前
2025中了 聊一聊程序员为什么都要做自己的产品
前端·harmonyos
幽蓝计划20 小时前
HarmonyOS NEXT仓颉开发语言实战案例:动态广场
华为·harmonyos
万少1 天前
第五款 HarmonyOS 上架作品 奇趣故事匣 来了
前端·harmonyos·客户端
幽蓝计划1 天前
HarmonyOS NEXT仓颉开发语言实战案例:电影App
华为·harmonyos
HMS Core1 天前
HarmonyOS免密认证方案 助力应用登录安全升级
安全·华为·harmonyos
生如夏花℡1 天前
HarmonyOS学习记录3
学习·ubuntu·harmonyos
伍哥的传说1 天前
鸿蒙系统(HarmonyOS)应用开发之手势锁屏密码锁(PatternLock)
前端·华为·前端框架·harmonyos·鸿蒙
遇到困难睡大觉哈哈2 天前
HarmonyOS 公共事件机制介绍以及多进程之间的通信实现(9000字详解)
华为·harmonyos
幽蓝计划2 天前
HarmonyOS NEXT仓颉开发语言实战案例:外卖App
开发语言·harmonyos