HarmonyOS应用《玄象》开发实战:十二律音频资源的 rawfile 加载与 AudioPlayer 生命周期管理

📅 2026/7/27 11:32:40 👁️ 阅读次数 📝 编程学习
HarmonyOS应用《玄象》开发实战:十二律音频资源的 rawfile 加载与 AudioPlayer 生命周期管理

阅读时长:约 18 分钟 | 难度:★★★★☆ | 篇章:第 9 篇 · 取名乐律地理 AI 助手 对应源码:entry/src/main/ets/pages/music/MusicTwelveLawsPage.ets

前言

玄象项目十二律吕页的音频资源存储在rawfile目录下,通过@ohos.multimedia.audioAudioPlayer播放。本篇将深入剖析玄象项目音频资源加载与播放的实现:从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