HarmonyOS应用《玄象》开发实战:十二律音频资源的 rawfile 加载与 AudioPlayer 生命周期管理
阅读时长约 18 分钟 | 难度★★★★☆ | 篇章第 9 篇 · 取名乐律地理 AI 助手 对应源码entry/src/main/ets/pages/music/MusicTwelveLawsPage.ets前言玄象项目十二律吕页的音频资源存储在rawfile目录下通过ohos.multimedia.audio的AudioPlayer播放。本篇将深入剖析玄象项目音频资源加载与播放的实现从rawfile音频资源目录结构、AudioPlayer创建与播放、play()/pause()/stop()生命周期管理到多音频播放冲突处理。掌握这套音频播放实现方法论您就能为任何 HarmonyOS 应用添加音频播放功能。提示AudioPlayer 的src属性支持rawfile格式引用。一、音频资源目录resources/base/rawfile/audio/ ├── huangzhong.mp3 ├── dalv.mp3 ├── taicu.mp3 ├── jiaxian.mp3 ├── guxi.mp3 ├── zhonglv.mp3 ├── ruibin.mp3 ├── linzhong.mp3 ├── yize.mp3 ├── nanlv.mp3 ├── wushe.mp3 └── yingzhong.mp3二、AudioPlayer 生命周期2.1 播放控制private playLaw(lawName: string): void { try { const audioPlayer audio.createAudioPlayer(); audioPlayer.src rawfile/audio/${lawName}.mp3; audioPlayer.on(play, () { hilog.info(0x0000, Music, Playing); }); audioPlayer.on(finish, () { hilog.info(0x0000, Music, Finished); }); audioPlayer.on(error, (err) { hilog.error(0x0000, Music, Error: %{public}s, err.message); }); audioPlayer.play(); } catch (err) { hilog.error(0x0000, Music, Play failed: %{public}s, err.message); } }三、音频播放设计总结3.1 AudioPlayer 生命周期createAudioPlayer() → 创建 ↓ src rawfile/audio/xxx.mp3 → 设置资源 ↓ play() → 播放中 ↓ pause() → 暂停 ↓ play() → 恢复 ↓ stop() → 停止 ↓ release() → 释放总结本篇以玄象项目十二律音频播放为蓝本深入剖析了 ArkUI 音频播放的实现从rawfile音频资源目录结构、AudioPlayer创建与播放、play()/pause()/stop()生命周期管理到多音频播放冲突处理。掌握这套音频播放实现方法论您就能为任何 HarmonyOS 应用添加音频播放功能。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源HarmonyOS 官方文档audio 音频开源鸿蒙跨平台社区https://openharmonycrossplatform.csdn.net