HarmonyOS 5.0.0 或以上:动态调节系统音量(含音量类型选择与范围控制)


📌 场景介绍

在媒体播放、游戏、闹钟、录音等应用中,动态调整系统音量是常见需求。本篇将实现:

  • 读取当前音量值

  • 调整媒体音量(不影响通话/通知)

  • 控制最大最小范围

  • 支持用户点击 + / - 操作修改音量


🧱 页面结构

/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 音量图标动态切换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值