In the scenario where multiple audio streams are concurrently playing, the system has preset a default audio focus strategy for unified audio focus management across all audio streams (including playback and recording).
When the default focus strategy provided by the system cannot meet app requirements, you can use the APIs provided by audio session management to manage the focus of audio streams within the app, customize the focus strategy for audio streams, and adjust the timing for releasing audio focus to meet specific needs. The sample code in this document is all ArkTS. If you need to use OHAudio for development, see Using OHAudio for Audio Session (C/C++).
Audio session management provides two focus management approaches: independent focus management for audio streams and unified focus management for an audio session. You can choose an appropriate focus management approach based on your own business requirements.
The audio session strategy set by either approach takes effect on all streams, and the activation and release timing is the same: activate before audio stream playback and release after it stops.
| Comparison Item | Independent Focus Management | Unified Focus Management |
|---|---|---|
| Focus management approach | AudioSession does not hold focus; each audio stream requests and releases focus independently. | AudioSession holds focus in a unified manner and manages the focus request and release of audio streams. |
| Applicable audio stream types | Applicable to both playback streams and recording streams. | Applicable to playback streams (except STREAM_USAGE_ALARM, STREAM_USAGE_NOTIFICATION, STREAM_USAGE_ACCESSIBILITY, and so on); not applicable to recording streams. |
The audio session APIs can be used to implement the following features:
Independent focus management for audio streams: The system default focus strategy cannot meet the current app requirements, and only the focus strategy of the audio stream needs to be adjusted.
Typical scenario: When an app plays a short video, it interrupts background music. The app expects the background music to automatically resume after its own audio stream stops. This scenario requires the app to activate the audio session before starting the audio stream and deactivate the audio session after the audio stream stops.
Unified focus management for an audio session: Multiple audio streams need to be started and the continuity of the playback process must be ensured, so as to prevent other apps' audio from resuming due to focus release when audio streams switch.
Typical scenario: When an app plays multiple audio clips consecutively, during the gaps between clips, the app does not want other affected background audio to automatically resume. Instead, it wants to maintain audio focus continuity throughout the entire playback process. This scenario requires the app to activate the audio session before the entire playback process starts and deactivate the audio session after the entire playback process ends.
Before using any APIs of AudioSessionManager, you must call getSessionManager to obtain a singleton AudioSessionManager instance.
For OHAudio development, see Obtaining an Audio Session Manager.
import { audio } from '@kit.AudioKit';
// ...
let audioManager = audio.getAudioManager();
// Create an audio session manager.
let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager(); When activating an AudioSession, you must first specify an audio session strategy (AudioSessionStrategy). You can specify different audio session strategies by setting the audio concurrency mode (AudioConcurrencyMode).
For OHAudio development, see Audio Session Strategy (OH_AudioSession_Strategy).
The system preset audio concurrency modes are as follows:
Default mode (CONCURRENCY_DEFAULT): The system default audio focus strategy.
Concurrency mode (CONCURRENCY_MIX_WITH_OTHERS): Plays concurrently with other audio streams.
Typical scenarios:
When an app plays music, it may be interrupted by subsequent music or video. The app expects its own audio stream to play concurrently with the subsequent music or video. (This scenario requires the app to activate the AudioSession before starting the audio stream.)
When an app records audio, it interrupts background music or video that is playing. The app expects its own audio stream to play concurrently with the background music or video. (This scenario requires the app to activate the AudioSession before starting the audio stream.)
Duck mode (CONCURRENCY_DUCK_OTHERS): Plays concurrently with other audio streams and reduces the volume of other audio streams.
Typical scenario: When an app plays game sound effects, it plays concurrently with background music. The app expects to lower the volume of the background music while playing concurrently with it. (This scenario requires the app to activate the AudioSession before starting the audio stream.)
Pause mode (CONCURRENCY_PAUSE_OTHERS): Pauses other audio streams and notifies them to resume after the focus is released.
Typical scenario: When an app plays a short video, it interrupts background music that is playing. The app expects the background music to automatically resume after its own audio stream stops. (This scenario requires the app to activate the AudioSession before starting the audio stream and deactivate the AudioSession after the audio stream stops.)
When the system default focus strategy cannot meet the current app requirements, you can modify the focus strategy by specifying an audio session strategy and then activating the AudioSession.
After the AudioSession is successfully activated, new audio streams started by the app will follow the modified focus strategy.
For OHAudio development, see Using OHAudio for Audio Session (C/C++).
When the AudioSession is deactivated due to timeout, the audio streams that were ducked by it will trigger an unduck operation, and the audio streams that were paused by it will trigger a stop operation.
When using AudioSession, it is recommended that you listen for the audio session deactivation event (AudioSessionDeactivatedEvent). When the AudioSession is deactivated (not proactively), the app receives this event notification. You can perform corresponding operations based on your service requirements, for example, releasing resources or reactivating the AudioSession.
The audio session deactivation event (AudioSessionDeactivatedEvent) contains the AudioSessionDeactivatedReason parameter, which identifies the specific reason for session deactivation (such as focus preemption or timeout).
App focus preempted (DEACTIVATED_LOWER_PRIORITY): When all audio streams of the app have their focus preempted by other apps, the AudioSession is deactivated at the same time.
Timeout (DEACTIVATED_TIMEOUT): If the AudioSession is in the activated state but the app has no audio stream running, the AudioSession will be deactivated after a specified period due to timeout.
Specify an audio session strategy (AudioSessionStrategy) and activate the audio session.
You can call activateAudioSession to activate the audio session of the current app.
When activating the AudioSession, you must specify an audio session strategy. The strategy contains the concurrencyMode parameter, which is of the AudioConcurrencyMode type and is used to declare the audio concurrency strategy.
import { audio } from '@kit.AudioKit';
import { BusinessError } from '@kit.BasicServicesKit';
// ...
// Set the audio concurrency mode.
let strategy: audio.AudioSessionStrategy = {
concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
};
// Activate the audio session.
audioSessionManager.activateAudioSession(strategy).then(() => {
console.info('Succeeded in activating audio session.');
// ...
}).catch((err: BusinessError) => {
console.error(`Failed to activate audio session. Code: ${err.code}, message: ${err.message}`);
// ...
}); Check whether the audio session is activated (optional).
You can call isAudioSessionActivated to check whether the audio session of the current app is activated.
// Check whether the audio session is activated. let isActivated = audioSessionManager.isAudioSessionActivated();
Listen for audio session deactivation events (optional).
You can call on('audioSessionDeactivated') to listen for audio session deactivation events (AudioSessionDeactivatedEvent).
When the AudioSession is deactivated (not proactively), the app receives an audio session deactivation event (AudioSessionDeactivatedEvent), which contains the audio session deactivation reason (AudioSessionDeactivatedReason).
Upon receiving AudioSessionDeactivatedEvent, you can perform corresponding operations based on your service requirements, for example, releasing resources or reactivating the AudioSession.
You can call off('audioSessionDeactivated') to cancel listening for audio session deactivation events.
import { audio } from '@kit.AudioKit';
// ...
// Listen for audio session deactivation events.
audioSessionManager.on('audioSessionDeactivated', (audioSessionDeactivatedEvent: audio.AudioSessionDeactivatedEvent) => {
// ...
console.info(`Succeeded in using on function. AudioSessionDeactivatedEvent: ${JSON.stringify(audioSessionDeactivatedEvent)}`);
}); Deactivate the audio session.
You can call deactivateAudioSession to deactivate the audio session of the current app.
After the AudioSession is deactivated, new audio streams started by the app will follow the default focus strategy.
import { BusinessError } from '@kit.BasicServicesKit';
// ...
// Deactivate the audio session.
// ...
audioSessionManager.deactivateAudioSession().then(() => {
console.info('Succeeded in deactivating audio session.');
// ...
}).catch((err: BusinessError) => {
console.error(`Failed to deactivate audio session. Code: ${err.code}, message: ${err.message}`);
// ...
}); The following shows the sample code for independent focus management for audio streams.
import { audio } from '@kit.AudioKit';
import { BusinessError } from '@kit.BasicServicesKit';
// ...
let audioManager = audio.getAudioManager();
// Create an audio session manager.
let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
// ...
// Set the audio concurrency mode.
let strategy: audio.AudioSessionStrategy = {
concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
};
// Activate the audio session.
audioSessionManager.activateAudioSession(strategy).then(() => {
console.info('Succeeded in activating audio session.');
// ...
}).catch((err: BusinessError) => {
console.error(`Failed to activate audio session. Code: ${err.code}, message: ${err.message}`);
// ...
});
// Check whether the audio session is activated.
let isActivated = audioSessionManager.isAudioSessionActivated();
// Listen for audio session deactivation events.
audioSessionManager.on('audioSessionDeactivated', (audioSessionDeactivatedEvent: audio.AudioSessionDeactivatedEvent) => {
// ...
console.info(`Succeeded in using on function. AudioSessionDeactivatedEvent: ${JSON.stringify(audioSessionDeactivatedEvent)}`);
});
if (isActivated) {
// After the audio session is activated, the app can perform audio playback, pause, stop, release, and other operations here.
}
// ...
// Stop listening for audio session deactivation events.
audioSessionManager.off('audioSessionDeactivated');
// ...
// Deactivate the audio session.
// ...
audioSessionManager.deactivateAudioSession().then(() => {
console.info('Succeeded in deactivating audio session.');
// ...
}).catch((err: BusinessError) => {
console.error(`Failed to deactivate audio session. Code: ${err.code}, message: ${err.message}`);
// ...
}); When an app needs to start multiple audio streams and ensure process continuity, you can request focus through AudioSession to ensure the continuity of multi-audio-stream playback.
When activating the AudioSession, the system requests the corresponding audio focus based on the audio session scene selected by the app, and the AudioSession holds the focus. Subsequent playback streams started by the app through AudioRenderer will no longer request audio focus.
For OHAudio development, see Using OHAudio for Audio Session (C/C++).
Typical usage scenarios are as follows:
When an audio session holds focus in a unified manner, the system provides three audio session scenes. Before activating the AudioSession, you must call setAudioSessionScene to set the corresponding audio session scene. When the AudioSession is activated, the system requests the corresponding audio focus based on the audio session scene selected by the app.
| Name | Value | Matching StreamUsage | Description | Applicable Scenario |
|---|---|---|---|---|
| AUDIO_SESSION_SCENE_MEDIA | 0 | STREAM_USAGE_MUSIC, STREAM_USAGE_MOVIE, STREAM_USAGE_AUDIOBOOK | Media audio session. | Scenarios where focus is frequently requested and released (for example, swiping through multiple short videos), and media playback scenarios where you do not hold an AudioRenderer object but need to listen for focus changes. |
| AUDIO_SESSION_SCENE_GAME | 1 | STREAM_USAGE_GAME | Game audio session. | Game audio scenarios such as in-game background music and voice-overs. |
| AUDIO_SESSION_SCENE_VOICE_COMMUNICATION | 2 | STREAM_USAGE_RINGTONE, STREAM_USAGE_VOICE_COMMUNICATION, STREAM_USAGE_VIDEO_COMMUNICATION | VoIP call audio session. | Call scenarios such as VoIP calls where a ringtone stream must be started simultaneously. |
If you do not use an audio session scene (AudioSessionScene) that matches the audio stream type (StreamUsage), the behavior of the audio stream may be inconsistent with expectations, causing the focus strategy to fail or playback to be abnormal.
The focus requested by AudioSession and the focus requested by AudioRenderer have equal status.
You can call on('audioSessionStateChanged') to listen for AudioSession focus and state changes. To maintain state consistency between the app and the system and ensure a good user experience, you should listen for AudioSession focus state events and respond accordingly when the focus changes.
on('audioSessionStateChanged') includes the information of AudioSession deactivation events. When unified focus management for an audio session is used, you do not need to additionally listen for audio session deactivation events (AudioSessionDeactivatedEvent).
If the app also registers focus event listening for AudioRenderer, note the following two points:
Specify an audio session scene (AudioSessionScene) and strategy (AudioSessionStrategy) and activate the audio session.
The app requests focus through AudioSession. First, call setAudioSessionScene to set the scene parameters, and then call activateAudioSession to activate the AudioSession. When the AudioSession is activated, the system requests the corresponding audio focus based on the audio session scene selected by the app.
import { audio } from '@kit.AudioKit';
import { BusinessError } from '@kit.BasicServicesKit';
// ...
// The app sets an appropriate audio session scenario based on its business scenario. When AudioSession is activated, the system requests the corresponding audio focus based on the audio session scenario selected by the app.
audioSessionManager.setAudioSessionScene(audio.AudioSessionScene.AUDIO_SESSION_SCENE_MEDIA);
// ...
// Set the audio session strategy.
let strategy: audio.AudioSessionStrategy = {
concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
};
// Activate AudioSession.
audioSessionManager.activateAudioSession(strategy).then(() => {
console.info('Succeeded in activating audio session.');
// ...
}).catch((err: BusinessError) => {
console.error(`Failed to activate audio session. Code: ${err.code}, message: ${err.message}`);
// ...
}); Check whether the audio session is activated (optional).
You can call isAudioSessionActivated to check whether the audio session of the current app is activated.
// Query whether the audio session is activated. let isActivated = audioSessionManager.isAudioSessionActivated();
Listen for AudioSession focus state change events.
You can call on('audioSessionStateChanged') to listen for AudioSession focus and state changes.
import { audio } from '@kit.AudioKit';
import { BusinessError } from '@kit.BasicServicesKit';
// ...
// Listen for AudioSession focus and state change events.
let audioSessionStateChangedCallback = (audioSessionStateChangedEvent: audio.AudioSessionStateChangedEvent) => {
// ...
console.info(`hint of audioSessionStateChanged: ${audioSessionStateChangedEvent.stateChangeHint} `);
switch (audioSessionStateChangedEvent.stateChangeHint) {
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_PAUSE:
// This branch indicates that the system has paused the audio stream. The app must switch to the audio paused state.
// Temporary focus loss: AudioSession is deactivated and releases focus, and all audio streams of the app are stopped. Therefore, after the app receives the Resume callback, it needs to reactivate AudioSession and resume the audio streams that need to continue playing.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_RESUME:
// This branch indicates that the system has lifted the pause on AudioSession focus.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_STOP:
// This branch indicates that the system has stopped the audio stream (permanent focus loss). To maintain state consistency, the app must switch to the audio paused state.
// Permanent focus loss: AudioSession is deactivated and releases focus, and all audio streams of the app are stopped. No further audio focus events will be received, and resuming playback requires user initiation.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_TIME_OUT_STOP:
// This branch indicates that the system has stopped AudioSession (permanent focus loss) due to prolonged inactivity of audio streams. The app must switch to the audio stopped state.
// Permanent focus loss: No further audio focus events will be received, and resuming playback requires user initiation.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_DUCK:
// This branch indicates that the system has reduced the volume of all playback audio streams of the app (to 20% of normal volume by default).
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_UNDUCK:
// This branch indicates that the system has restored the volume of all playback audio streams of the app to normal.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_MUTE_SUGGESTION:
// This branch indicates that another app has started playing non-mixable audio. The system may decide whether to mute.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_UNMUTE_SUGGESTION:
// This branch indicates that the non-mixable audio playback of another app has ended. The system may decide whether to unmute.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_MUTE:
// This branch indicates that the system has muted all playback audio streams of the app.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_UNMUTE:
// This branch indicates that the system has unmuted all playback audio streams of the app.
break;
default:
break;
}
};
audioSessionManager.on('audioSessionStateChanged', audioSessionStateChangedCallback); Deactivate the audio session.
You can call deactivateAudioSession to deactivate the audio session of the current app.
When the AudioSession is deactivated, the system releases the focus requested by the AudioSession and stops all audio streams being played by the app.
import { BusinessError } from '@kit.BasicServicesKit';
// ...
// Deactivate AudioSession, that is, release the focus and deactivate all audio streams being played by the app.
audioSessionManager.deactivateAudioSession().then(() => {
console.info('Succeeded in deactivating audio session.');
// ...
}).catch((err: BusinessError) => {
console.error(`Failed to deactivate audio session. Code: ${err.code}, message: ${err.message}`);
// ...
}); The following shows the sample code for unified focus management for an audio session.
import { audio } from '@kit.AudioKit';
import { BusinessError } from '@kit.BasicServicesKit';
// ...
// The app sets an audio session scenario suitable for its business needs. When AudioSession is activated, the system requests the corresponding audio focus based on the audio session scenario selected by the app.
audioSessionManager.setAudioSessionScene(audio.AudioSessionScene.AUDIO_SESSION_SCENE_MEDIA);
// ...
// Set the audio session strategy.
let strategy: audio.AudioSessionStrategy = {
concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
};
// Activate AudioSession.
audioSessionManager.activateAudioSession(strategy).then(() => {
console.info('Succeeded in activating audio session.');
// ...
}).catch((err: BusinessError) => {
console.error(`Failed to activate audio session. Code: ${err.code}, message: ${err.message}`);
// ...
});
// Listen for AudioSession focus and state change events.
let audioSessionStateChangedCallback = (audioSessionStateChangedEvent: audio.AudioSessionStateChangedEvent) => {
// ...
console.info(`hint of audioSessionStateChanged: ${audioSessionStateChangedEvent.stateChangeHint} `);
switch (audioSessionStateChangedEvent.stateChangeHint) {
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_PAUSE:
// This branch indicates that the system has paused the audio stream. The app must switch to the audio paused state.
// Temporary focus loss: AudioSession is deactivated and releases focus, and all audio streams of the app are stopped. Therefore, after the app receives the Resume callback, it needs to reactivate AudioSession and resume the audio streams that need to continue playing.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_RESUME:
// This branch indicates that the system has lifted the pause on AudioSession focus.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_STOP:
// This branch indicates that the system has stopped the audio stream (permanent focus loss). To maintain state consistency, the app must switch to the audio paused state.
// Permanent focus loss: AudioSession is deactivated and releases focus, and all audio streams of the app are stopped. No further audio focus events will be received, and playback can only be resumed when triggered by the user.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_TIME_OUT_STOP:
// This branch indicates that the system has stopped AudioSession (permanent focus loss) due to prolonged inactivity of audio stream playback. The app must switch to the audio stopped state.
// Permanent focus loss: No further audio focus events will be received, and playback can only be resumed when triggered by the user.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_DUCK:
// This branch indicates that the system has reduced the volume of all playback audio streams of the app (to 20% of the normal volume by default).
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_UNDUCK:
// This branch indicates that the system has restored the volume of all playback audio streams of the app to normal.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_MUTE_SUGGESTION:
// This branch indicates that another app has started playing non-mixable audio. The system may decide whether to mute at its own discretion.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_UNMUTE_SUGGESTION:
// This branch indicates that the non-mixable audio playback of another app has ended. The system may decide whether to unmute at its own discretion.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_MUTE:
// This branch indicates that the system has muted all playback audio streams of the app.
break;
case audio.AudioSessionStateChangeHint.AUDIO_SESSION_STATE_CHANGE_HINT_UNMUTE:
// This branch indicates that the system has unmuted all playback audio streams of the app.
break;
default:
break;
}
};
audioSessionManager.on('audioSessionStateChanged', audioSessionStateChangedCallback);
// Query whether the audio session is activated.
let isActivated = audioSessionManager.isAudioSessionActivated();
if (isActivated) {
// After the audio session is activated, the app can perform normal audio operations such as play, pause, stop, and release here.
// Based on actual business needs, the app can start multiple AudioRenderer audio playback streams. The audio playback streams started here no longer hold focus individually; they are managed by AudioSession.
// If multiple audio streams are playing simultaneously, pay special attention to the timing of AudioSession deactivation (deactivating AudioSession also releases all audio playback streams of the app).
}
// ...
// When the service ends, stop listening for AudioSession focus and state change events.
audioSessionManager.off('audioSessionStateChanged');
// ...
// Deactivate AudioSession, which releases focus and stops all audio streams currently being played by the app.
audioSessionManager.deactivateAudioSession().then(() => {
console.info('Succeeded in deactivating audio session.');
// ...
}).catch((err: BusinessError) => {
console.error(`Failed to deactivate audio session. Code: ${err.code}, message: ${err.message}`);
// ...
}); Starting from API version 24, when an app has muted the recording stream in the current audio session on the service side, you can call setCapturerMuteHint to report this state to the system audio module. The system audio module adjusts its strategy based on the reported state to reduce power consumption. Note that this feature currently takes effect only on certain PCs/2-in-1 devices. This API does not actually trigger muting or perform mute processing on recording data. It only notifies the system audio module that the app has muted the recording stream in the current audio session. You still need to handle the recording data yourself, for example, by not sending captured data or by sending mute data.
This API can only be called when there is a running recording stream in the current audio session. Otherwise, error code 6800103 is returned. If a recording stream has both the stream-level mute hint API AudioCapturer.setMuteHint and the session-level mute hint API called, the stream-level setting takes precedence. Therefore, when the mute states of multiple recording streams in the app are consistent, you can use the session-level API for unified reporting. When the mute states of different recording streams are inconsistent, use the stream-level API for specific recording streams. If you create a Mic audio source recording stream to call the session-level API, you need to request the microphone permission ohos.permission.MICROPHONE. No system query API is currently provided. If you need to display the mute hint state on the UI, you must maintain the most recently set state yourself. In the following example, muteHint set to true indicates reporting a mute hint, and false indicates canceling the mute hint.
try {
await audioSessionManager.setCapturerMuteHint(muteHint);
console.info(`setCapturerMuteHint ${muteHint} success.`);
// ...
} catch (err) {
let error = err as BusinessError;
console.error(`setCapturerMuteHint ${muteHint} failed. Code: ${error.code}, message: ${error.message}`);
// ...
} Starting from API version 23, when the current application plays audio in the CONCURRENCY_MIX_WITH_OTHERS concurrency mode, if audio from other applications is playing simultaneously, the audio from both will be mixed. In certain scenarios (such as games or broadcasts), applications can enable mute suggestion notifications to enhance user experience.
After enabling mute suggestion notifications, if other applications play audio that cannot be played concurrently with the current application while the current application is playing audio, the current application will receive a mute suggestion notification. The current application can either choose to take no action (allowing concurrent playback with other applications) or mute itself to let other applications play audio alone.
To enable mute suggestion notifications for mixed playback, you need to first call setAudioSessionScene to set the scene parameters, call enableMuteSuggestionWhenMixWithOthers to enable the mute suggestion notification feature, subscribe to audio session state change events AudioSessionStateChangedEvent, and finally call activateAudioSession to activate the AudioSession. The prerequisite for enabling mute suggestion notifications is that the AudioConcurrencyMode mode must be CONCURRENCY_MIX_WITH_OTHERS.
import { audio } from '@kit.AudioKit';
import { BusinessError } from '@kit.BasicServicesKit';
// ...
// The app sets an appropriate audio session scenario based on the service scenario. When AudioSession is activated, the system requests the corresponding audio focus based on the audio session scenario selected by the app.
audioSessionManager.setAudioSessionScene(audio.AudioSessionScene.AUDIO_SESSION_SCENE_MEDIA);
// This API takes effect only when called before the audio session is activated.
audioSessionManager.enableMuteSuggestionWhenMixWithOthers(true);
// Set the audio session strategy.
let strategy: audio.AudioSessionStrategy = {
concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
};
// Activate AudioSession.
audioSessionManager.activateAudioSession(strategy).then(() => {
console.info('Succeeded in activating audio session.');
// ...
}).catch((err: BusinessError) => {
console.error(`Failed to activate audio session. Code: ${err.code}, message: ${err.message}`);
// ...
}); Starting from API version 24, you can call setAudioSessionBehavior to set audio session behavior parameters for a better audio focus experience in specific scenarios.
In a live streaming scenario, when another app starts an audio stream (such as using a keyboard for speech-to-text) that interrupts the live stream, the live stream's audio and video are paused, affecting the viewing experience. A live streaming app can set the AudioSessionBehaviorFlags.MUTE_WHEN_INTERRUPTED session behavior to keep the live stream playing in mute mode instead of pausing when interrupted, thereby avoiding video interruption.
If your app does not use audio session management, you can also set independent audio session behavior for a single audio stream. For playback streams, see setIndependentAudioSessionStrategy. For recording streams, see setIndependentAudioSessionStrategy.
import { audio } from '@kit.AudioKit';
import { BusinessError } from '@kit.BasicServicesKit';
// ...
// The app sets an appropriate audio session scenario based on its service requirements. When AudioSession is activated, the system requests the corresponding audio focus based on the audio session scenario selected by the app.
audioSessionManager.setAudioSessionScene(audio.AudioSessionScene.AUDIO_SESSION_SCENE_MEDIA);
// Call this API before activating the audio session.
// If this API is called while the audio session is active, you must reactivate the audio session for the changes to take effect.
let behavior = audio.AudioSessionBehaviorFlags.MUTE_WHEN_INTERRUPTED;
audioSessionManager.setAudioSessionBehavior(behavior);
// Set the audio session strategy.
let strategy: audio.AudioSessionStrategy = {
concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_PAUSE_OTHERS
};
// Activate the AudioSession.
audioSessionManager.activateAudioSession(strategy).then(() => {
console.info('Succeeded in activating audio session.');
}).catch((err: BusinessError) => {
console.error(`Failed to activate audio session. Code: ${err.code}, message: ${err.message}`);
});