HarmonyOS 鸿蒙Next soundPool如何播放沙盒路径下的音频文件

HarmonyOS 鸿蒙Next soundPool如何播放沙盒路径下的音频文件

const filePath = '/data/storage/el2/base/haps/entry/files/drainage_audio.wav'
文件path是这样的,请问如何将地址转成fd
9 回复

参考下面代码:

const rawFile: resourceManager.RawFileDescriptor = this.resourceManager.getRawFdSync("technology.mp3");
Logger.info(TAG, "file id: " + rawFile.fd + ", file size: " + rawFile.length);
this.soundPoolParam.soundId = await this.soundPoolParam.soundPool?.load(rawFile.fd, rawFile.offset, rawFile.length);

完整代码如下:

const TAG: string = "AudioVm";

class SoundPoolParam {
  soundPool?: media.SoundPool;
  soundId?: number;
  streamId?: number;
}

export class AudioVm {
  private context: Context;
  private resourceManager: resourceManager.ResourceManager;
  private soundPoolParam: SoundPoolParam = new SoundPoolParam();
  constructor(context: Context) {
    this.context = context;
    this.resourceManager = context.resourceManager;
  }

  public async soundPoolPlay() {
    //创建soundPool实例
    Logger.info(TAG, "soundPoolPlay");
    let audioRendererInfo: audio.AudioRendererInfo = {
      usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
      rendererFlags: 0
    }
    try {
      this.soundPoolParam.soundPool = await media.createSoundPool(5, audioRendererInfo);
      this.soundPoolParam.soundPool.on("playFinished", () => {
        Logger.info(TAG, "soundPoolPlay finished");
        this.soundPoolStop();
      });
      this.soundPoolParam.soundPool.on("error", (err: BusinessError) => {
        Logger.info(TAG, "soundPoolPlay error: " + JSON.stringify(err));
        this.soundPoolStop();
      });
      this.soundPoolParam.soundPool.on("loadComplete", (event: number) => {
        Logger.info(TAG, "soundPoolPlay loadComplete");
        this.soundPoolParam.soundPool?.play(this.soundPoolParam.soundId, (err: BusinessError, streamId: number) => {
          this.soundPoolParam.streamId = streamId;
        });
      })
      const rawFile: resourceManager.RawFileDescriptor = this.resourceManager.getRawFdSync("technology.mp3");
      Logger.info(TAG, "file id: " + rawFile.fd + ", file size: " + rawFile.length);
      this.soundPoolParam.soundId = await this.soundPoolParam.soundPool?.load(rawFile.fd, rawFile.offset, rawFile.length);
    } catch (e) {
      Logger.info(TAG, "soundPoolPlay exception: " + JSON.stringify(e));
    }
  }

  public async soundPoolStop() {
    Logger.info(TAG, "soundPoolStop");
    try {
      if (this.soundPoolParam && this.soundPoolParam.soundPool) {
        if (this.soundPoolParam.streamId) {
          await this.soundPoolParam.soundPool.stop(this.soundPoolParam.streamId);
        }
        if (this.soundPoolParam.soundId) {
          await this.soundPoolParam.soundPool.unload(this.soundPoolParam.soundId);
        }
        this.soundPoolParam.soundPool.off("playFinished");
        this.soundPoolParam.soundPool.off("loadComplete");
        this.soundPoolParam.soundPool.off("error");
        await this.soundPoolParam.soundPool.release();
      }
    } catch (e) {
      Logger.info(TAG, "soundPoolStop exception: " + JSON.stringify(e));
    }
  }
}

更多关于HarmonyOS 鸿蒙Next soundPool如何播放沙盒路径下的音频文件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


你的写法不行,我贴一下我试出来的结果,

| 姓名 | 张三 |
| --- | --- |
| 年龄 | 28 |
| 职位 | 经理 |

![](http://example.com/image.png)
const filePath = getContext(this).filesDir + '/drainage_audio.wav'
fs.open(filePath, fs.OpenMode.READ_ONLY, (err, fd) => {
  if (err) {
    console.error('播放音频   Failed to open file:', err);
    return;
  }
  console.info("播放音频   file id: " + fd.fd + ", file size: " );
  // 加载音频文件
  if (this.soundPool){
    this.soundPool.load(fd.fd, 0, fs.statSync(filePath).size, (error: BusinessError, soundId_: number) => {
      if (error) {
        console.error(`播放音频   Failed to load soundPool: errCode is ${error.code}, errMessage is ${error.message}`);
      } else {
        this.soundID = soundId_;
        console.info('播放音频   Succeeded in loading soundId:' + this.soundID);
      }
    });
  }
})
最终的答案,实际测试可用

感谢分享!

let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
file.fd

load(fd: number, offset: number, length: number): Promise<number>;

你这个 openSync 我试过了,但是 offsetlength 就没法获取到了。

const fd = context.resourceManager.getRawFdSync('find_ear_tips.wav');

这个获取到的 fd 的类型是 RawFileDescriptor,这里面的属性就很多,能满足需求,但是用不到沙盒里面的音频。

你是想获取文件信息吗?试试:fs.statSync(),

this.soundPool.load(fd.fd, fd.offset, fd.length, (
  error: BusinessError, soundId_: number
) => {
  if (error) {
    console.error(`播放音频   Failed to load soundPool: errCode is ${error.code}, errMessage is ${error.message}`);
  } else {
    this.soundID = soundId_;
    console.info('播放音频   Succeeded in loading soundId:' + this.soundID);
  }
});

soundPool.load函数里面的参数,fd如何获得

在HarmonyOS(鸿蒙)系统中,使用Next soundPool播放沙盒路径下的音频文件,可以通过以下步骤实现:

  1. 获取沙盒路径下的音频文件URI: 首先,你需要获取到存储在沙盒路径(如应用私有存储目录)下的音频文件的URI。这通常是通过文件管理器(FileManager)来完成的,你可以使用应用上下文来获取沙盒目录,并拼接具体的文件名来构建文件路径。

  2. 创建SoundPool实例: 使用HarmonyOS提供的SoundPool API来创建一个SoundPool实例。这个实例将用于管理和播放音频文件。

  3. 加载音频文件: 使用SoundPool的load方法,并传入音频文件的URI,来加载音频文件到SoundPool中。这个方法会返回一个音频ID,用于后续的播放控制。

  4. 播放音频: 加载完成后,使用SoundPool的play方法,并传入音频ID,来播放音频文件。

请注意,由于HarmonyOS系统的API可能会随着版本更新而有所变化,因此上述步骤中的具体方法调用和参数可能会有所不同。建议参考最新的HarmonyOS开发文档来获取最准确的信息。

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

回到顶部