📌 场景介绍
在媒体播放、游戏、闹钟、录音等应用中,动态调整系统音量是常见需求。本篇将实现:
-
读取当前音量值
-
调整媒体音量(不影响通话/通知)
-
控制最大最小范围
-
支持用户点击 + / - 操作修改音量
🧱 页面结构
/entry/src/main/ets
└── pages/
└── VolumeControlDemo.ets // 音量调节示例页
🧩 VolumeControlDemo.ets 示例页面
import audio from '@ohos.multimedia.audio'
@Entry
@Component
struct VolumeControlDemo {
@State currentVolume: number = 0
@State maxVolume: number = 15
private volumeManager: audio.AudioManager | undefined
async aboutToAppear() {
try {
this.volumeManager = await audio.getAudioManager()
this.maxVolume = await this.volumeManager.getMaxVolume(audio.StreamType.STREAM_MUSIC)
this.currentVolume = await this.volumeManager.getVolume(audio.StreamType.STREAM_MUSIC)
} catch (err) {
console.error('获取音量失败:', JSON.stringify(err))
}
}
private async setVolume(up: boolean) {
if (!this.volumeManager) return
let newVolume = up ? this.currentVolume + 1 : this.currentVolume - 1
newVolume = Math.max(0, Math.min(this.maxVolume, newVolume))
try {
await this.volumeManager.setVolume(audio.StreamType.STREAM_MUSIC, newVolume)
this.currentVolume = newVolume
} catch (err) {
console.error('设置音量失败:', JSON.stringify(err))
}
}
build() {
Column() {
Text("🔊 当前媒体音量").fontSize(22).margin({ bottom: 20 })
Text(`音量:${this.currentVolume} / ${this.maxVolume}`).fontSize(18).margin({ bottom: 10 })
Row() {
Button("-").width(60).onClick(() => this.setVolume(false)).margin(10)
Button("+").width(60).onClick(() => this.setVolume(true)).margin(10)
}
}
.padding(30)
.height('100%')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
}
✅ 效果说明
-
页面显示当前媒体音量值
-
用户点击“+”“-”动态调整音量
-
音量值始终限制在 0 ~ 最大值之间
🔧 拓展建议
-
增加滑动条调节音量(Slider)
-
设置通知音量、通话音量(更换
StreamType
) -
音量变化联动 UI 音量图标动态切换