• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Volume Management
2
3You can use different APIs to manage the system volume and audio stream volume. The system volume and audio stream volume refer to the volume of a OpenHarmony device and the volume of a specified audio stream, respectively. The audio stream volume is restricted by the system volume.
4
5## System Volume
6
7The API for managing the system volume is **AudioVolumeManager**. Before using this API, you must call **getVolumeManager()** to obtain an **AudioVolumeManager** instance. Currently, this API can be used to obtain volume information and listen for volume changes. It cannot be used to adjust the system volume.
8
9```ts
10import audio from '@ohos.multimedia.audio';
11let audioManager = audio.getAudioManager();
12let audioVolumeManager = audioManager.getVolumeManager();
13```
14
15### Listening for System Volume Changes
16
17You can set an event to listen for system volume changes.
18
19```ts
20audioVolumeManager.on('volumeChange', (volumeEvent) => {
21  console.info(`VolumeType of stream: ${volumeEvent.volumeType} `);
22  console.info(`Volume level: ${volumeEvent.volume} `);
23  console.info(`Whether to updateUI: ${volumeEvent.updateUi} `);
24});
25```
26
27### Adjusting the System Volume (for System Applications Only)
28
29Currently, the system volume is mainly adjusted by using system APIs, which serve the physical volume button and the Settings application. When the user presses the volume button, a system API is called to adjust the system volume, including the volume for media, ringtone, or notification.
30
31## Audio Stream Volume
32
33The API for managing the audio stream volume is **setVolume()** in the **AVPlayer** or **AudioRenderer** class. The code snippet below is used for setting the audio stream volume by using the **AVPlayer** class:
34
35```ts
36let volume = 1.0 // Specified volume. The value range is [0.00-1.00]. The value 1 indicates the maximum volume.
37avPlayer.setVolume(volume)
38```
39
40The code snippet below is used for setting the audio stream volume by using the **AudioRenderer** class:
41
42```ts
43audioRenderer.setVolume(0.5).then(data=>{ // The volume range is [0.0-1.0].
44  console.info('Invoke setVolume succeeded.');
45}).catch((err) => {
46  console.error(`Invoke setVolume failed, code is ${err.code}, message is ${err.message}`);
47});
48```
49