完整代码示例如下:
import { BusinessError } from '@kit.BasicServicesKit'; import { audio, AVVolumePanel } from '@kit.AudioKit'; import { LengthMetrics, LengthUnit, ArcButton, ArcButtonOptions, ArcButtonStatus, ArcButtonStyleMode, ArcButtonPosition, } from '@kit.ArkUI'; @Entry @ComponentV2 struct Index { @Local topOptions: ArcButtonOptions = new ArcButtonOptions({}); @Local bottomOptions: ArcButtonOptions = new ArcButtonOptions({}); @Local volume: number = 0; initVolume() { try { this.volume = audio.getAudioManager().getVolumeManager().getVolumeByStream(audio.StreamUsage.STREAM_USAGE_MUSIC); } catch (err) { let error = err as BusinessError; console.error(`Failed to obtains the volume of a stream, error: ${error}`); } } aboutToAppear(): void { this.initVolume(); this.topOptions = new ArcButtonOptions({ label: '调高音量', status: ArcButtonStatus.NORMAL, position: ArcButtonPosition.TOP_EDGE, styleMode: ArcButtonStyleMode.NORMAL_LIGHT, fontSize: new LengthMetrics(15, LengthUnit.FP), shadowEnabled: true, onClick: () => { if (this.volume < 15) { this.volume++; } let audioManager = audio.getAudioManager(); let audioVolumeManager = audioManager.getVolumeManager(); try { audioVolumeManager.on('streamVolumeChange', audio.StreamUsage.STREAM_USAGE_MUSIC, (streamVolumeEvent: audio.StreamVolumeEvent) => { console.info(`StreamUsage of stream: ${streamVolumeEvent.streamUsage} `); console.info(`Volume level: ${streamVolumeEvent.volume} `); this.getUIContext().getPromptAction().showToast({ message: `当前音量为:${streamVolumeEvent.volume}`, duration: 2000 }); }); } catch (error) { console.error(`Failed to listen for stream volume change events, error: ${error}`); } } }); this.bottomOptions = new ArcButtonOptions({ label: '调低音量', styleMode: ArcButtonStyleMode.NORMAL_LIGHT, fontSize: new LengthMetrics(15, LengthUnit.FP), shadowEnabled: true, onClick: () => { if (this.volume > 0) { this.volume--; } let audioManager = audio.getAudioManager(); let audioVolumeManager = audioManager.getVolumeManager(); try { audioVolumeManager.on('streamVolumeChange', audio.StreamUsage.STREAM_USAGE_MUSIC, (streamVolumeEvent: audio.StreamVolumeEvent) => { console.info(`StreamUsage of stream: ${streamVolumeEvent.streamUsage} `); console.info(`Volume level: ${streamVolumeEvent.volume} `); this.getUIContext().getPromptAction().showToast({ message: `当前音量为:${streamVolumeEvent.volume}`, duration: 2000 }); }); } catch (error) { console.error(`Failed to listen for stream volume change events, error: ${error}`); } } }); } build() { Stack() { AVVolumePanel({ volumeLevel: this.volume, volumeParameter: { position: { x: 0, y: 0 } } }).width('100%').height('100%'); Column() { ArcButton({ options: this.topOptions }); Blank(); ArcButton({ options: this.bottomOptions }); }.width('100%').height('100%'); }.width(233).height(233); } }