HarmonyOS 鸿蒙Next 使用SoundPool播放mp3短音频实现快速点击正常播放且次数一致

HarmonyOS 鸿蒙Next 使用SoundPool播放mp3短音频实现快速点击正常播放且次数一致 使用SoundPool播放mp3短音频,能支持快速点击,音频也能够正常的播放,播放次数与点击次数一致,请提供代码示例

3 回复

加载rawfile下资源,需要将文档中加载方式换为rawfile的方式,可以参考代码

import {ResourceManager} from '@ohos.resourceManager';
getContext().resourceManager.getRawFd("1.mp3").then((value: ResourceManager.RawFileDescriptor) => {
  let fd = value.fd;
  let offset = value.offset;
  let length = value.length;
  soundPool.load(fd,offset,length).then((soundIdd: number) => {
    console.info('加载音频load success:',soundIdd);
    soundId=soundIdd;
  });
});

更多关于HarmonyOS 鸿蒙Next 使用SoundPool播放mp3短音频实现快速点击正常播放且次数一致的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


这个偶尔也会导致播放多次,明明就点击一个播放。

在HarmonyOS鸿蒙Next系统中,使用SoundPool播放mp3短音频并实现快速点击时正常播放且次数一致,可以通过以下步骤实现:

  1. 初始化SoundPool: 创建一个SoundPool实例,并设置音频的最大流数、音频类型和质量等参数。例如:

    SoundPool soundPool = new SoundPool.Builder()
        .setMaxStreams(5)
        .setAudioAttributes(new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build())
        .build();
    
  2. 加载音频文件: 使用soundPool.load()方法加载mp3文件,该方法返回一个音频ID,用于后续播放。

  3. 播放音频: 在快速点击事件中,使用soundPool.play()方法播放音频。为了确保播放次数一致,可以在播放前检查是否有未播放完毕的音频,并适当处理(如忽略新请求或停止当前播放)。

  4. 释放资源: 当不再需要SoundPool时,调用soundPool.release()释放资源。

注意,SoundPool适用于播放短音频,对于长音频或需要精确控制播放进度的情况,建议使用MediaPlayer。

如果问题依旧没法解决请联系官网客服, 官网地址是 https://www.itying.com/category-93-b0.html

回到顶部