提交 91cde005 编写于 作者: G Gloria

Update docs against 11001+11539+11708+12000+11919

Signed-off-by: wusongqing<wusongqing@huawei.com>
上级 7224a63f
# AVSession Development
## Development for the Session Access End
### Basic Concepts
- **AVMetadata**: media data related attributes, including the IDs of the current media asset, previous media asset, and next media asset, title, author, album, writer, and duration.
- **AVSessionDescriptor**: descriptor about a media session, including the session ID, session type (audio/video), custom session name (**sessionTag**), and information about the corresponding application (**elementName**).
- **AVPlaybackState**: information related to the media playback state, including the playback state, position, speed, buffered time, loop mode, and whether the media asset is favorited (**isFavorite**).
### Available APIs
The table below lists the APIs available for the development of the session access end. The APIs use either a callback or promise to return the result. The APIs listed below use a callback, which provide the same functions as their counterparts that use a promise. For details, see [AVSession Management](../reference/apis/js-apis-avsession.md).
Table 1 Common APIs for session access end development
| API | Description |
|----------------------------------------------------------------------------------|-------------|
| createAVSession(context: Context, tag: string, type: AVSessionType, callback: AsyncCallback\<AVSession>): void | Creates a session.|
| setAVMetadata(data: AVMetadata, callback: AsyncCallback\<void>): void | Sets session metadata. |
| setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback\<void>): void | Sets the playback state information. |
| setLaunchAbility(ability: WantAgent, callback: AsyncCallback\<void>): void | Sets the launcher ability.|
| getController(callback: AsyncCallback\<AVSessionController>): void | Obtains the controller of this session.|
| getOutputDevice(callback: AsyncCallback\<OutputDeviceInfo>): void | Obtains the output device information. |
| activate(callback: AsyncCallback\<void>): void | Activates this session. |
| destroy(callback: AsyncCallback\<void>): void | Destroys this session. |
### How to Develop
1. Import the modules.
```js
import avSession from '@ohos.multimedia.avsession';
import wantAgent from '@ohos.wantAgent';
import featureAbility from '@ohos.ability.featureAbility';
```
2. Create and activate a session.
```js
// Define global variables.
let mediaFavorite = false;
let currentSession = null;
let context = featureAbility.getContext();
// Create an audio session.
avSession.createAVSession(context, "AudioAppSample", 'audio').then((session) => {
currentSession = session;
currentSession.activate(); // Activate the session.
}).catch((err) => {
console.info(`createAVSession : ERROR : ${err.message}`);
});
```
3. Set the session information, including:
- Session metadata. In addition to the current media asset ID (mandatory), you can set the title, album, author, duration, and previous/next media asset ID. For details about the session metadata, see **AVMetadata** in the API document.
- Launcher ability, which is implemented by calling an API of **WantAgent**. Generally, **WantAgent** is used to encapsulate want information. For more information, see [wantAgent](../reference/apis/js-apis-wantAgent.md).
- Playback state information.
```js
// Set the session metadata.
let metadata = {
assetId: "121278",
title: "lose yourself",
artist: "Eminem",
author: "ST",
album: "Slim shady",
writer: "ST",
composer: "ST",
duration: 2222,
mediaImage: "https://www.example.com/example.jpg", // Set it based on your project requirements.
subtitle: "8 Mile",
description: "Rap",
lyric: "https://www.example.com/example.lrc", // Set it based on your project requirements.
previousAssetId: "121277",
nextAssetId: "121279",
};
currentSession.setAVMetadata(metadata).then(() => {
console.info('setAVMetadata successfully');
}).catch((err) => {
console.info(`setAVMetadata : ERROR : ${err.message}`);
});
```
```js
// Set the launcher ability.
let wantAgentInfo = {
wants: [
{
bundleName: "com.neu.setResultOnAbilityResultTest1",
abilityName: "com.example.test.MainAbility",
}
],
operationType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}
wantAgent.getWantAgent(wantAgentInfo).then((agent) => {
currentSession.setLaunchAbility(agent).then(() => {
console.info('setLaunchAbility successfully');
}).catch((err) => {
console.info(`setLaunchAbility : ERROR : ${err.message}`);
});
});
```
```js
// Set the playback state information.
let PlaybackState = {
state: avSession.PlaybackState.PLAYBACK_STATE_STOP,
speed: 1.0,
position:{elapsedTime: 0, updateTime: (new Date()).getTime()},
bufferedTime: 1000,
loopMode: avSession.LoopMode.LOOP_MODE_SEQUENCE,
isFavorite: false,
};
currentSession.setAVPlaybackState(PlaybackState).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
console.info(`setAVPlaybackState : ERROR : ${err.message}`);
});
```
```js
// Obtain the controller of this session.
currentSession.getController().then((selfController) => {
console.info('getController successfully');
}).catch((err) => {
console.info(`getController : ERROR : ${err.message}`);
});
```
```js
// Obtain the output device information.
currentSession.getOutputDevice().then((outputInfo) => {
console.info(`getOutputDevice successfully, deviceName : ${outputInfo.deviceName}`);
}).catch((err) => {
console.info(`getOutputDevice : ERROR : ${err.message}`);
});
```
4. Subscribe to control command events.
```js
// Subscribe to the 'play' command event.
currentSession.on('play', () => {
console.log ("Call AudioPlayer.play.");
// Set the playback state information.
currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PLAY}).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
console.info(`setAVPlaybackState : ERROR : ${err.message}`);
});
});
// Subscribe to the 'pause' command event.
currentSession.on('pause', () => {
console.log ("Call AudioPlayer.pause.");
// Set the playback state information.
currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PAUSE}).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
console.info(`setAVPlaybackState : ERROR : ${err.message}`);
});
});
// Subscribe to the 'stop' command event.
currentSession.on('stop', () => {
console.log ("Call AudioPlayer.stop.");
// Set the playback state information.
currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_STOP}).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
console.info(`setAVPlaybackState : ERROR : ${err.message}`);
});
});
// Subscribe to the 'playNext' command event.
currentSession.on('playNext', () => {
// When the media file is not ready, download and cache the media file, and set the 'PREPARE' state.
currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PREPARE}).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
console.info(`setAVPlaybackState : ERROR : ${err.message}`);
});
// The media file is obtained.
currentSession.setAVMetadata({assetId: '58970105', title: 'See you tomorrow'}).then(() => {
console.info('setAVMetadata successfully');
}).catch((err) => {
console.info(`setAVMetadata : ERROR : ${err.message}`);
});
console.log ("Call AudioPlayer.play.");
// Set the playback state information.
let time = (new Data()).getTime();
currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PLAY, position: {elapsedTime: 0, updateTime: time}, bufferedTime:2000}).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
console.info(`setAVPlaybackState : ERROR : ${err.message}`);
});
});
// Subscribe to the 'fastForward' command event.
currentSession.on('fastForward', () => {
console.log("Call AudioPlayer for fast forwarding.");
// Set the playback state information.
currentSession.setAVPlaybackState({speed: 2.0}).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
console.info(`setAVPlaybackState : ERROR : ${err.message}`);
});
});
// Subscribe to the 'seek' command event.
currentSession.on('seek', (time) => {
console.log("Call AudioPlayer.seek.");
// Set the playback state information.
currentSession.setAVPlaybackState({position: {elapsedTime: time, updateTime: (new Data()).getTime()}}).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
console.info(`setAVPlaybackState : ERROR : ${err.message}`);
});
});
// Subscribe to the 'setSpeed' command event.
currentSession.on('setSpeed', (speed) => {
console.log(`Call AudioPlayer to set the speed to ${speed}`);
// Set the playback state information.
currentSession.setAVPlaybackState({speed: speed}).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
console.info(`setAVPlaybackState : ERROR : ${err.message}`);
});
});
// Subscribe to the 'setLoopMode' command event.
currentSession.on('setLoopMode', (mode) => {
console.log(`The application switches to the loop mode ${mode}`);
// Set the playback state information.
currentSession.setAVPlaybackState({loopMode: mode}).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
console.info(`setAVPlaybackState : ERROR : ${err.message}`);
});
});
// Subscribe to the 'toggleFavorite' command event.
currentSession.on('toggleFavorite', (assetId) => {
console.log(`The application favorites ${assetId}.`);
// Perform the switch based on the last status.
let favorite = mediaFavorite == false ? true : false;
currentSession.setAVPlaybackState({isFavorite: favorite}).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
console.info(`setAVPlaybackState : ERROR : ${err.message}`);
});
mediaFavorite = favorite;
});
// Subscribe to the key event.
currentSession.on('handleKeyEvent', (event) => {
console.log(`User presses the key ${event.keyCode}`);
});
// Subscribe to output device changes.
currentSession.on('outputDeviceChange', (device) => {
console.log(`Output device changed to ${device.deviceName}`);
});
```
5. Release resources.
```js
// Unsubscribe from the events.
currentSession.off('play');
currentSession.off('pause');
currentSession.off('stop');
currentSession.off('playNext');
currentSession.off('playPrevious');
currentSession.off('fastForward');
currentSession.off('rewind');
currentSession.off('seek');
currentSession.off('setSpeed');
currentSession.off('setLoopMode');
currentSession.off('toggleFavorite');
currentSession.off('handleKeyEvent');
currentSession.off('outputDeviceChange');
// Deactivate the session and destroy the object.
currentSession.deactivate().then(() => {
currentSession.destory();
});
```
### Verification
Touch the play, pause, or next button on the media application. Check whether the media playback state changes accordingly.
### FAQs
1. Session Service Exception
- Symptoms
The session service is abnormal, and the application cannot obtain a response from the session service. For example, the session service is not running or the communication with the session service fails. The error message "Session service exception" is displayed.
- Possible causes
The session service is killed during session restart.
- Solution
(1) The system retries the operation automatically. If the error persists for 3 seconds or more, stop the operation on the session or controller.
(2) Destroy the current session or session controller and re-create it. If the re-creation fails, stop the operation on the session.
2. Session Does Not Exist
- Symptoms
Parameters are set for or commands are sent to the session that does not exist. The error message "The session does not exist" is displayed.
- Possible causes
The session has been destroyed, and no session record exists on the server.
- Solution
(1) If the error occurs on the application, re-create the session. If the error occurs on Media Controller, stop sending query or control commands to the session.
(2) If the error occurs on the session service, query the current session record and pass the correct session ID when creating the controller.
3. Session Not Activated
- Symptoms
A control command or event is sent to the session when it is not activated. The error message "The session not active" is displayed.
- Possible causes
The session is in the inactive state.
- Solution
Stop sending the command or event. Subscribe to the session activation status, and resume the sending when the session is activated.
## Development for the Session Control End (Media Controller)
### Basic Concepts
- Remote projection: A local media session is projected to a remote device. The local controller sends commands to control media playback on the remote device.
- Sending key events: The controller controls media playback by sending key events.
- Sending control commands: The controller controls media playback by sending control commands.
- Sending system key events: A system application calls APIs to send system key events to control media playback.
- Sending system control commands: A system application calls APIs to send system control commands to control media playback.
### Available APIs
The table below lists the APIs available for the development of the session control end. The APIs use either a callback or promise to return the result. The APIs listed below use a callback, which provide the same functions as their counterparts that use a promise. For details, see [AVSession Management](../reference/apis/js-apis-avsession.md).
Table 2 Common APIs for session control end development
| API | Description |
| ------------------------------------------------------------------------------------------------ | ----------------- |
| getAllSessionDescriptors(callback: AsyncCallback\<Array\<Readonly\<AVSessionDescriptor>>>): void | Obtains the descriptors of all sessions. |
| createController(sessionId: string, callback: AsyncCallback\<AVSessionController>): void | Creates a controller. |
| sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback\<void>): void | Sends a key event. |
| getLaunchAbility(callback: AsyncCallback\<WantAgent>): void | Obtains the launcher ability. |
| sendControlCommand(command: AVControlCommand, callback: AsyncCallback\<void>): void | Sends a control command. |
| sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback\<void>): void | Send a system key event. |
| sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback\<void>): void | Sends a system control command. |
| castAudio(session: SessionToken \| 'all', audioDevices: Array\<audio.AudioDeviceDescriptor>, callback: AsyncCallback\<void>): void | Casts the media session to a remote device.|
### How to Develop
1. Import the modules.
```js
import avSession from '@ohos.multimedia.avsession';
import {Action, KeyEvent} from '@ohos.multimodalInput.KeyEvent';
import wantAgent from '@ohos.wantAgent';
import audio from '@ohos.multimedia.audio';
```
2. Obtain the session descriptors and create a controller.
```js
// Define global variables.
let g_controller = new Array<avSession.AVSessionController>();
let g_centerSupportCmd:Set<avSession.AVControlCommandType> = new Set(['play', 'pause', 'playNext', 'playPrevious', 'fastForward', 'rewind', 'seek','setSpeed', 'setLoopMode', 'toggleFavorite']);
let g_validCmd:Set<avSession.AVControlCommandType>;
// Obtain the session descriptors and create a controller.
avSession.getAllSessionDescriptors().then((descriptors) => {
descriptors.forEach((descriptor) => {
avSession.createController(descriptor.sessionId).then((controller) => {
g_controller.push(controller);
}).catch((err) => {
console.error('createController error');
});
});
}).catch((err) => {
console.error('getAllSessionDescriptors error');
});
// Subscribe to the 'sessionCreate' event and create a controller.
avSession.on('sessionCreate', (session) => {
// After a session is added, you must create a controller.
avSession.createController(session.sessionId).then((controller) => {
g_controller.push(controller);
}).catch((err) => {
console.info(`createController : ERROR : ${err.message}`);
});
});
```
3. Subscribe to the session state and service changes.
```js
// Subscribe to the 'activeStateChange' event.
controller.on('activeStateChange', (isActive) => {
if (isActive) {
console.log ("The widget corresponding to the controller is highlighted.");
} else {
console.log("The widget corresponding to the controller is invalid.");
}
});
// Subscribe to the 'sessionDestroy' event to enable Media Controller to get notified when the session dies.
controller.on('sessionDestroy', () => {
console.info('on sessionDestroy : SUCCESS ');
controller.destroy().then(() => {
console.info('destroy : SUCCESS ');
}).catch((err) => {
console.info(`destroy : ERROR :${err.message}`);
});
});
// Subscribe to the 'sessionDestroy' event to enable the application to get notified when the session dies.
avSession.on('sessionDestroy', (session) => {
let index = g_controller.findIndex((controller) => {
return controller.sessionId == session.sessionId;
});
if (index != 0) {
g_controller[index].destroy();
g_controller.splice(index, 1);
}
});
// Subscribe to the 'topSessionChange' event.
avSession.on('topSessionChange', (session) => {
let index = g_controller.findIndex((controller) => {
return controller.sessionId == session.sessionId;
});
// Place the session on the top.
if (index != 0) {
g_controller.sort((a, b) => {
return a.sessionId == session.sessionId ? -1 : 0;
});
}
});
// Subscribe to the 'sessionServiceDie' event.
avSession.on('sessionServiceDie', () => {
// The server is abnormal, and the application clears resources.
console.log("Server exception");
})
```
4. Subscribe to media session information changes.
```js
// Subscribe to metadata changes.
let metaFilter = ['assetId', 'title', 'description'];
controller.on('metadataChange', metaFilter, (metadata) => {
console.info(`on metadataChange assetId : ${metadata.assetId}`);
});
// Subscribe to playback state changes.
let playbackFilter = ['state', 'speed', 'loopMode'];
controller.on('playbackStateChange', playbackFilter, (playbackState) => {
console.info(`on playbackStateChange state : ${playbackState.state}`);
});
// Subscribe to supported command changes.
controller.on('validCommandChange', (cmds) => {
console.info(`validCommandChange : SUCCESS : size : ${cmds.size}`);
console.info(`validCommandChange : SUCCESS : cmds : ${cmds.values()}`);
g_validCmd.clear();
for (let c of g_centerSupportCmd) {
if (cmds.has(c)) {
g_validCmd.add(c);
}
}
});
// Subscribe to output device changes.
controller.on('outputDeviceChange', (device) => {
console.info(`on outputDeviceChange device isRemote : ${device.isRemote}`);
});
```
5. Control the session behavior.
```js
// When the user touches the play button, the control command 'play' is sent to the session.
if (g_validCmd.has('play')) {
controller.sendControlCommand({command:'play'}).then(() => {
console.info('sendControlCommand successfully');
}).catch((err) => {
console.info(`sendControlCommand : ERROR : ${err.message}`);
});
}
// When the user selects the single loop mode, the corresponding control command is sent to the session.
if (g_validCmd.has('setLoopMode')) {
controller.sendControlCommand({command: 'setLoopMode', parameter: avSession.LoopMode.LOOP_MODE_SINGLE}).then(() => {
console.info('sendControlCommand successfully');
}).catch((err) => {
console.info(`sendControlCommand : ERROR : ${err.message}`);
});
}
// Send a key event.
let keyItem = {code: 0x49, pressedTime: 123456789, deviceId: 0};
let event = {action: 2, key: keyItem, keys: [keyItem]};
controller.sendAVKeyEvent(event).then(() => {
console.info('sendAVKeyEvent Successfully');
}).catch((err) => {
console.info(`sendAVKeyEvent : ERROR : ${err.message}`);
});
// The user touches the blank area on the widget to start the application.
controller.getLaunchAbility().then((want) => {
console.log("Starting the application in the foreground");
}).catch((err) => {
console.info(`getLaunchAbility : ERROR : ${err.message}`);
});
// Send the system key event.
let keyItem = {code: 0x49, pressedTime: 123456789, deviceId: 0};
let event = {action: 2, key: keyItem, keys: [keyItem]};
avSession.sendSystemAVKeyEvent(event).then(() => {
console.info('sendSystemAVKeyEvent Successfully');
}).catch((err) => {
console.info(`sendSystemAVKeyEvent : ERROR : ${err.message}`);
});
// Send a system control command to the top session.
let avcommand = {command: 'toggleFavorite', parameter: "false"};
avSession.sendSystemControlCommand(avcommand).then(() => {
console.info('sendSystemControlCommand successfully');
}).catch((err) => {
console.info(`sendSystemControlCommand : ERROR : ${err.message}`);
});
// Cast the session to another device.
let audioManager = audio.getAudioManager();
let audioDevices;
await audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
audioDevices = data;
console.info('Promise returned to indicate that the device list is obtained.');
}).catch((err) => {
console.info(`getDevices : ERROR : ${err.message}`);
});
avSession.castAudio('all', audioDevices).then(() => {
console.info('createController : SUCCESS');
}).catch((err) => {
console.info(`createController : ERROR : ${err.message}`);
});
```
6. Release resources.
```js
// Unsubscribe from the events.
controller.off('metadataChange');
controller.off('playbackStateChange');
controller.off('sessionDestroy');
controller.off('activeStateChange');
controller.off('validCommandChange');
controller.off('outputDeviceChange');
// Destroy the controller.
controller.destroy().then(() => {
console.info('destroy : SUCCESS ');
}).catch((err) => {
console.info(`destroy : ERROR : ${err.message}`);
});
```
### Verification
When you touch the play, pause, or next button in Media Controller, the playback state of the application changes accordingly.
### FAQs
1. Controller Does Not Exist
- Symptoms
A control command or an event is sent to the controller that does not exist. The error message "The session controller does not exist" is displayed.
- Possible causes
The controller has been destroyed.
- Solution
Query the session record and create the corresponding controller.
2. Remote Session Connection Failure
- Symptoms
The communication between the local session and the remote session fails. The error information "The remote session connection failed" is displayed.
- Possible causes
The communication between devices is interrupted.
- Solution
Stop sending control commands to the session. Subscribe to output device changes, and resume the sending when the output device is changed.
3. Invalid Session Command
- Symptoms
The control command or event sent to the session is not supported. The error message "Invalid session command" is displayed.
- Possible causes
The session does not support this command.
- Solution
Stop sending the command or event. Query the commands supported by the session, and send a command supported.
4. Too Many Commands or Events
- Symptoms
The session client sends too many messages or commands to the server in a period of time, causing the server to be overloaded. The error message "Command or event overload" is displayed.
- Possible causes
The server is overloaded with messages or events.
- Solution
Control the frequency of sending commands or events.
# AVSession Overview
## Overview
AVSession, short for audio and video session, is also known as media session.
- Application developers can use the APIs provided by the **AVSession** module to connect their audio and video applications to the system's Media Controller.
- System developers can use the APIs provided by the **AVSession** module to display media information of system audio and video applications and carry out unified playback control.
You can implement the following features through the **AVSession** module:
1. Unified playback control entry
If there are multiple audio and video applications on the device, users need to switch to and access different applications to control media playback. With AVSession, a unified playback control entry of the system (such as Media Controller) is used for playback control of these audio and video applications. No more switching is required.
2. Better background application management
When an application running in the background automatically starts audio playback, it is difficult for users to locate the application. With AVSession, users can quickly find the application that plays the audio clip in Media Controller.
## Basic Concepts
- AVSession
A channel used for information exchange between applications and Media Controller. For AVSession, one end is the media application under control, and the other end is Media Controller. Through AVSession, an application can transfer the media playback information to Media Controller and receive control commands from Media Controller.
- AVSessionController
Object that controls media sessions and thereby controls the playback behavior of applications. Through AVSessionController, Media Controller can control the playback behavior of applications, obtain playback information, and send control commands. It can also monitor the playback state of applications to ensure synchronization of the media session information.
- Media Controller
Holder of AVSessionController. Through AVSessionController, Media Controller sends commands to control media playback of applications.
## Implementation Principle
The **AVSession** module provides two classes: **AVSession** and **AVSessionController**.
**Figure 1** AVSession interaction
![en-us_image_avsession](figures/en-us_image_avsession.png)
- Interaction between the application and Media Controller: First, an audio application creates an **AVSession** object and sets session information, including media metadata, launcher ability, and playback state information. Then, Media Controller creates an **AVSessionController** object to obtain session-related information and send the 'play' command to the audio application. Finally, the audio application responds to the command and updates the playback state.
- Distributed projection: When a connected device creates a local session, Media Controller or the audio application can select another device to be projected based on the device list, synchronize the local session to the remote device, and generate a controllable remote session. The remote session is controlled by sending control commands to the remote device's application through its AVSessionController.
## Constraints
- The playback information displayed in Media Controller is the media information proactively written by the media application to AVSession.
- Media Controller controls the playback of a media application based on the responses of the media application to control commands.
- AVSession can transmit media playback information and control commands. It does not display information or execute control commands.
- Do not develop Media Controller for common applications. For common audio and video applications running on OpenHarmony, the default control end is Media Controller, which is a system application. You do not need to carry out additional development for Media Controller.
- If you want to develop your own system running OpenHarmony, you can develop your own Media Controller.
- For better background management of audio and video applications, the **AVSession** module enforces background control for third-party applications. Only third-party applications that have accessed AVSession can play audio in the background. Otherwise, the system forcibly pauses the playback when a third-party application switches to the background.
# AVSession Management
The **avSession** module provides APIs for media playback control so that applications can access the system's Media Controller.
This module provides the following common features related to media sessions:
- [AVSession](#section652893): used to set session metadata, playback state information, and more.
- [AVSessionController](#section974602): used to obtain session IDs, send commands and events to sessions, and obtain the session metadata and playback state information.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
import avSession from '@ohos.multimedia.avsession';
```
## avSession.createAVSession
createAVSession(context: Context, tag: string, type: AVSessionType): Promise\<AVSession>
Creates a media session. This API uses a promise to return the result. An ability can have only one session, and repeated calling of this API fails.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------- | ---- | ------------------------------ |
| context| [Context](../../ability/context-userguide.md) | Yes| Application context, which provides application environment information.|
| tag | string | Yes | Custom session name. |
| type | [AVSessionType](#avsessiontype) | Yes | Session type, which can be audio or video.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------------------------------ |
| Promise<[AVSession](#avsession)\> | Promise used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
**Example**
```js
import featureAbility from '@ohos.ability.featureAbility';
let session;
let tag = "createNewSession";
let context = featureAbility.getContext();
await avSession.createAVSession(context, tag, "audio").then((data) => {
session = data;
console.info(`CreateAVSession : SUCCESS : sessionId = ${session.sessionId}`);
}).catch((err) => {
console.info(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
## avSession.createAVSession
createAVSession(context: Context, tag: string, type: AVSessionType, callback: AsyncCallback\<AVSession>): void
Creates a media session. This API uses an asynchronous callback to return the result. An ability can have only one session, and repeated calling of this API fails.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| context| [Context](../../ability/context-userguide.md) | Yes| Application context, which provides application environment information. |
| tag | string | Yes | Custom session name. |
| type | [AVSessionType](#avsessiontype) | Yes | Session type, which can be audio or video. |
| callback | AsyncCallback<[AVSession](#avsession)\> | Yes | Callback used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
**Example**
```js
import featureAbility from '@ohos.ability.featureAbility';
let session;
let tag = "createNewSession";
let context = featureAbility.getContext();
avSession.createAVSession(context, tag, "audio", function (err, data) {
if (err) {
console.info(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
session = data;
console.info(`CreateAVSession : SUCCESS : sessionId = ${session.sessionId}`);
}
});
```
## avSession.getAllSessionDescriptors
getAllSessionDescriptors(): Promise\<Array\<Readonly\<AVSessionDescriptor>>>
Obtains the descriptors of all sessions. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Return value**
| Type | Description |
| ------------------------------------------------------------ | --------------------------------------------- |
| Promise\<Array\<Readonly\<[AVSessionDescriptor](#avsessiondescriptor)\>\>\> | Promise used to return an array of **AVSessionDescriptor** objects, each of which is read only.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
**Example**
```js
avSession.getAllSessionDescriptors().then((descriptors) => {
console.info(`getAllSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`);
if(descriptors.length > 0 ){
console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`);
console.info(`GetAllSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`);
console.info(`GetAllSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`);
}
}).catch((err) => {
console.info(`GetAllSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
## avSession.getAllSessionDescriptors
getAllSessionDescriptors(callback: AsyncCallback\<Array\<Readonly\<AVSessionDescriptor>>>): void
Obtains the descriptors of all sessions. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ |
| callback | AsyncCallback<Array<Readonly<[AVSessionDescriptor](#avsessiondescriptor)\>\>\> | Yes | Callback used to return an array of **AVSessionDescriptor** objects, each of which is read only.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 |Session service exception |
**Example**
```js
avSession.getAllSessionDescriptors(function (err, descriptors) {
if (err) {
console.info(`GetAllSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info(`GetAllSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`);
if(descriptors.length > 0 ){
console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`);
console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`);
console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`);
}
}
});
```
## avSession.createController
createController(sessionId: string): Promise\<AVSessionController>
Creates a session controller based on the session ID. Multiple session controllers can be created. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | -------- |
| sessionId | string | Yes | Session ID.|
**Return value**
| Type | Description |
| ----------------------------------------------------- | ------------------------------------------------------------ |
| Promise<[AVSessionController](#avsessioncontroller)\> | Promise used to return the session controller created, which can be used to obtain the session ID,<br>send commands and events to sessions, and obtain metadata and playback state information.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
import featureAbility from '@ohos.ability.featureAbility';
let session;
let tag = "createNewSession";
let context = featureAbility.getContext();
await avSession.createAVSession(context, tag, "audio").then((data) => {
session = data;
console.info(`CreateAVSession : SUCCESS : sessionId = ${session.sessionId}`);
}).catch((err) => {
console.info(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
});
let controller;
await avSession.createController(session.sessionId).then((avcontroller) => {
controller = avcontroller;
console.info(`CreateController : SUCCESS : ${controller.sessionId}`);
}).catch((err) => {
console.info(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
## avSession.createController
createController(sessionId: string, callback: AsyncCallback\<AVSessionController>): void
Creates a session controller based on the session ID. Multiple session controllers can be created. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| sessionId | string | Yes | Session ID. |
| callback | AsyncCallback<[AVSessionController](#avsessioncontroller)\> | Yes | Callback used to return the session controller created, which can be used to obtain the session ID,<br>send commands and events to sessions, and obtain metadata and playback state information.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
import featureAbility from '@ohos.ability.featureAbility';
let session;
let tag = "createNewSession";
let context = featureAbility.getContext();
await avSession.createAVSession(context, tag, "audio").then((data) => {
session = data;
console.info(`CreateAVSession : SUCCESS : sessionId = ${session.sessionId}`);
}).catch((err) => {
console.info(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
});
let controller;
avSession.createController(session.sessionId, function (err, avcontroller) {
if (err) {
console.info(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
controller = avcontroller;
console.info(`CreateController : SUCCESS : ${controller.sessionId}`);
}
});
```
## avSession.castAudio
castAudio(session: SessionToken | 'all', audioDevices: Array<audio.AudioDeviceDescriptor>): Promise\<void>
Casts a session to a list of devices. This API uses a promise to return the result.
Before calling this API, import the **ohos.multimedia.audio** module to obtain the descriptors of these audio devices.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ |--------------------------------------------------------------------------------------------------------------------------------------------------------------------| ---- | ------------------------------------------------------------ |
| session | [SessionToken](#sessiontoken) &#124; 'all' | Yes | Session token. **SessionToken** indicates a specific token, and **'all'** indicates all tokens.|
| audioDevices | Array\<[audio.AudioDeviceDescriptor](js-apis-audio.md#audiodevicedescriptor)\> | Yes | Audio devices. |
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the cast is successful, no value is returned; otherwise, an error object is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600104 | The remote session connection failed |
**Example**
```js
import audio from '@ohos.multimedia.audio';
let audioManager = audio.getAudioManager();
let audioDevices;
await audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
audioDevices = data;
console.info('Promise returned to indicate that the device list is obtained.');
}).catch((err) => {
console.info(`GetDevices BusinessError: code: ${err.code}, message: ${err.message}`);
});
avSession.castAudio('all', audioDevices).then(() => {
console.info('CreateController : SUCCESS');
}).catch((err) => {
console.info(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
## avSession.castAudio
castAudio(session: SessionToken | 'all', audioDevices: Array<audio.AudioDeviceDescriptor>, callback: AsyncCallback\<void>): void
Casts a session to a list of devices. This API uses an asynchronous callback to return the result.
Before calling this API, import the **ohos.multimedia.audio** module to obtain the descriptors of these audio devices.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ |--------------------------------------------| ---- | ------------------------------------------------------------ |
| session | [SessionToken](#sessiontoken) &#124; 'all' | Yes | Session token. **SessionToken** indicates a specific token, and **'all'** indicates all tokens.|
| audioDevices | Array\<[audio.AudioDeviceDescriptor](js-apis-audio.md#audiodevicedescriptor)\> | Yes | Audio devices. |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the casting is successful, **err** is **undefined**; otherwise, **err** is an error object. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600104 | The remote session connection failed |
**Example**
```js
import audio from '@ohos.multimedia.audio';
let audioManager = audio.getAudioManager();
let audioDevices;
await audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
audioDevices = data;
console.info('Promise returned to indicate that the device list is obtained.');
}).catch((err) => {
console.info(`GetDevices BusinessError: code: ${err.code}, message: ${err.message}`);
});
avSession.castAudio('all', audioDevices, function (err) {
if (err) {
console.info(`CastAudio BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('CastAudio : SUCCESS ');
}
});
```
## avSession.on('sessionCreate' | 'sessionDestroy' | 'topSessionChange')
on(type: 'sessionCreate' | 'sessionDestroy' | 'topSessionChange', callback: (session: AVSessionDescriptor) => void): void
Subscribes to session creation, session destruction, and top session change events.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **'sessionCreate'**: session creation event, which is reported when a session is created.<br>- **'sessionDestroy'**: session destruction event, which is reported when a session is destroyed.<br>- **'topSessionChange'**: top session change event, which is reported when the top session is changed.|
| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | Yes | Callback used to report the session descriptor. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
**Example**
```js
avSession.on('sessionCreate', (descriptor) => {
console.info(`on sessionCreate : isActive : ${descriptor.isActive}`);
console.info(`on sessionCreate : type : ${descriptor.type}`);
console.info(`on sessionCreate : sessionTag : ${descriptor.sessionTag}`);
});
avSession.on('sessionDestroy', (descriptor) => {
console.info(`on sessionDestroy : isActive : ${descriptor.isActive}`);
console.info(`on sessionDestroy : type : ${descriptor.type}`);
console.info(`on sessionDestroy : sessionTag : ${descriptor.sessionTag}`);
});
avSession.on('topSessionChange', (descriptor) => {
console.info(`on topSessionChange : isActive : ${descriptor.isActive}`);
console.info(`on topSessionChange : type : ${descriptor.type}`);
console.info(`on topSessionChange : sessionTag : ${descriptor.sessionTag}`);
});
```
## avSession.off('sessionCreate' | 'sessionDestroy' | 'topSessionChange')
off(type: 'sessionCreate' | 'sessionDestroy' | 'topSessionChange', callback?: (session: AVSessionDescriptor) => void): void
Unsubscribes from session creation, session destruction, and top session change events.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **'sessionCreate'**: session creation event, which is reported when a session is created.<br>- **'sessionDestroy'**: session destruction event, which is reported when a session is destroyed.<br>- **'topSessionChange'**: top session change event, which is reported when the top session is changed.|
| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **session** parameter in the callback describes a media session. The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
**Example**
```js
avSession.off('sessionCreate');
avSession.off('sessionDestroy');
avSession.off('topSessionChange');
```
## avSession.on('sessionServiceDie')
on(type: 'sessionServiceDie', callback: () => void): void
Subscribes to session service death events.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'sessionServiceDie'** is reported when the session service dies.|
| callback | callback: () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
**Example**
```js
avSession.on('sessionServiceDie', () => {
console.info('on sessionServiceDie : session is Died ');
});
```
## avSession.off('sessionServiceDie')
off(type: 'sessionServiceDie', callback?: () => void): void
Unsubscribes from session service death events.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ---------------------- | ---- | ------------------------------------------------------- |
| type | string | Yes | Event type. The event **'sessionServiceDie'** is reported when the session service dies.|
| callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
**Example**
```js
avSession.off('sessionServiceDie');
```
## avSession.sendSystemAVKeyEvent
sendSystemAVKeyEvent(event: KeyEvent): Promise\<void>
Sends a system key event to the top session. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------- | ---- | ---------- |
| event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event.|
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600105 | Invalid session command |
**Example**
```js
let keyItem = {code:0x49, pressedTime:2, deviceId:0};
let event = {id:1, deviceId:0, actionTime:1, screenId:1, windowId:1, action:2, key:keyItem, unicodeChar:0, keys:[keyItem], ctrlKey:false, altKey:false, shiftKey:false, logoKey:false, fnKey:false, capsLock:false, numLock:false, scrollLock:false};
avSession.sendSystemAVKeyEvent(event).then(() => {
console.info('SendSystemAVKeyEvent Successfully');
}).catch((err) => {
console.info(`SendSystemAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
## avSession.sendSystemAVKeyEvent
sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback\<void>): void
Sends a system key event to the top session. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------- |
| event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event. |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600105 | Invalid session command |
**Example**
```js
let keyItem = {code:0x49, pressedTime:2, deviceId:0};
let event = {id:1, deviceId:0, actionTime:1, screenId:1, windowId:1, action:2, key:keyItem, unicodeChar:0, keys:[keyItem], ctrlKey:false, altKey:false, shiftKey:false, logoKey:false, fnKey:false, capsLock:false, numLock:false, scrollLock:false};
avSession.sendSystemAVKeyEvent(event, function (err) {
if (err) {
console.info(`SendSystemAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('SendSystemAVKeyEvent : SUCCESS ');
}
});
```
## avSession.sendSystemControlCommand
sendSystemControlCommand(command: AVControlCommand): Promise\<void>
Sends a system control command to the top session. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------------------- |
| command | [AVControlCommand](#avcontrolcommand) | Yes | Command to send.|
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600105 | Invalid session command |
| 6600107 | Command or event overload |
**Example**
```js
let cmd : avSession.AVControlCommandType = 'play';
// let cmd : avSession.AVControlCommandType = 'pause';
// let cmd : avSession.AVControlCommandType = 'stop';
// let cmd : avSession.AVControlCommandType = 'playNext';
// let cmd : avSession.AVControlCommandType = 'playPrevious';
// let cmd : avSession.AVControlCommandType = 'fastForward';
// let cmd : avSession.AVControlCommandType = 'rewind';
let avcommand = {command:cmd};
// let cmd : avSession.AVControlCommandType = 'seek';
// let avcommand = {command:cmd, parameter:10};
// let cmd : avSession.AVControlCommandType = 'setSpeed';
// let avcommand = {command:cmd, parameter:2.6};
// let cmd : avSession.AVControlCommandType = 'setLoopMode';
// let avcommand = {command:cmd, parameter:avSession.LoopMode.LOOP_MODE_SINGLE};
// let cmd : avSession.AVControlCommandType = 'toggleFavorite';
// let avcommand = {command:cmd, parameter:"false"};
avSession.sendSystemControlCommand(avcommand).then(() => {
console.info('SendSystemControlCommand successfully');
}).catch((err) => {
console.info(`SendSystemControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
## avSession.sendSystemControlCommand
sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback\<void>): void
Sends a system control command to the top session. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ------------------------------------- |
| command | [AVControlCommand](#avcontrolcommand) | Yes | Command to send. |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600105 | Invalid session command |
| 6600107 | Command or event overload |
**Example**
```js
let cmd : avSession.AVControlCommandType = 'play';
// let cmd : avSession.AVControlCommandType = 'pause';
// let cmd : avSession.AVControlCommandType = 'stop';
// let cmd : avSession.AVControlCommandType = 'playNext';
// let cmd : avSession.AVControlCommandType = 'playPrevious';
// let cmd : avSession.AVControlCommandType = 'fastForward';
// let cmd : avSession.AVControlCommandType = 'rewind';
let avcommand = {command:cmd};
// let cmd : avSession.AVControlCommandType = 'seek';
// let avcommand = {command:cmd, parameter:10};
// let cmd : avSession.AVControlCommandType = 'setSpeed';
// let avcommand = {command:cmd, parameter:2.6};
// let cmd : avSession.AVControlCommandType = 'setLoopMode';
// let avcommand = {command:cmd, parameter:avSession.LoopMode.LOOP_MODE_SINGLE};
// let cmd : avSession.AVControlCommandType = 'toggleFavorite';
// let avcommand = {command:cmd, parameter:"false"};
avSession.sendSystemControlCommand(avcommand, function (err) {
if (err) {
console.info(`SendSystemControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('sendSystemControlCommand successfully');
}
});
```
## AVSession<a name="section652893"></a>
An **AVSession** object is created by calling [avSession.createAVSession](#avsessioncreateavsession). The object enables you to obtain the session ID and set the metadata and playback state.
### Attributes
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Type | Readable| Writable| Description |
| :-------- | :----- | :--- | :--- | :---------------------------- |
| sessionId | string | Yes | No | Unique session ID of the **AVSession** object.|
**Example**
```js
let sessionId = session.sessionId;
```
### setAVMetadata
setAVMetadata(data: AVMetadata): Promise\<void>
Sets session metadata. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------- | ---- | ------------ |
| data | [AVMetadata](#avmetadata) | Yes | Session metadata.|
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
let metadata = {
assetId: "121278",
title: "lose yourself",
artist: "Eminem",
author: "ST",
album: "Slim shady",
writer: "ST",
composer: "ST",
duration: 2222,
mediaImage: "https://www.example.com/example.jpg",
subtitle: "8 Mile",
description: "Rap",
lyric: "https://www.example.com/example.lrc",
previousAssetId: "121277",
nextAssetId: "121279",
};
session.setAVMetadata(metadata).then(() => {
console.info('SetAVMetadata successfully');
}).catch((err) => {
console.info(`SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### setAVMetadata
setAVMetadata(data: AVMetadata, callback: AsyncCallback\<void>): void
Sets session metadata. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------- |
| data | [AVMetadata](#avmetadata) | Yes | Session metadata. |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
let metadata = {
assetId: "121278",
title: "lose yourself",
artist: "Eminem",
author: "ST",
album: "Slim shady",
writer: "ST",
composer: "ST",
duration: 2222,
mediaImage: "https://www.example.com/example.jpg",
subtitle: "8 Mile",
description: "Rap",
lyric: "https://www.example.com/example.lrc",
previousAssetId: "121277",
nextAssetId: "121279",
};
session.setAVMetadata(metadata, function (err) {
if (err) {
console.info(`SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('SetAVMetadata successfully');
}
});
```
### setAVPlaybackState
setAVPlaybackState(state: AVPlaybackState): Promise\<void>
Sets information related to the session playback state. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------- | ---- | ---------------------------------------------- |
| data | [AVPlaybackState](#avplaybackstate) | Yes | Information related to the session playback state.|
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
let playbackState = {
state:avSession.PlaybackState.PLAYBACK_STATE_PLAY,
speed: 1.0,
position:{elapsedTime:10, updateTime:(new Date()).getTime()},
bufferedTime:1000,
loopMode:avSession.LoopMode.LOOP_MODE_SINGLE,
isFavorite:true,
};
session.setAVPlaybackState(playbackState).then(() => {
console.info('SetAVPlaybackState successfully');
}).catch((err) => {
console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### setAVPlaybackState
setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback\<void>): void
Sets information related to the session playback state. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ---------------------------------------------- |
| data | [AVPlaybackState](#avplaybackstate) | Yes | Information related to the session playback state.|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
let PlaybackState = {
state:avSession.PlaybackState.PLAYBACK_STATE_PLAY,
speed: 1.0,
position:{elapsedTime:10, updateTime:(new Date()).getTime()},
bufferedTime:1000,
loopMode:avSession.LoopMode.LOOP_MODE_SINGLE,
isFavorite:true,
};
session.setAVPlaybackState(PlaybackState, function (err) {
if (err) {
console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('SetAVPlaybackState successfully');
}
});
```
### setLaunchAbility
setLaunchAbility(ability: WantAgent): Promise\<void>
Sets a launcher ability. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | --------------------------------- | ---- | ----------------------------------------------------------- |
| ability | [WantAgent](js-apis-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID.|
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
import wantAgent from '@ohos.wantAgent';
// WantAgentInfo object
let wantAgentInfo = {
wants: [
{
deviceId: "deviceId",
bundleName: "com.neu.setResultOnAbilityResultTest1",
abilityName: "com.example.test.MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters:
{
mykey0: 2222,
mykey1: [1, 2, 3],
mykey2: "[1, 2, 3]",
mykey3: "ssssssssssssssssssssssssss",
mykey4: [false, true, false],
mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"],
mykey6: true,
}
}
],
operationType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}
wantAgent.getWantAgent(wantAgentInfo).then((agent) => {
session.setLaunchAbility(agent).then(() => {
console.info('SetLaunchAbility successfully');
}).catch((err) => {
console.info(`SetLaunchAbility BusinessError: code: ${err.code}, message: ${err.message}`);
});
});
```
### setLaunchAbility
setLaunchAbility(ability: WantAgent, callback: AsyncCallback\<void>): void
Sets a launcher ability. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------- | ---- | ----------------------------------------------------------- |
| ability | [WantAgent](js-apis-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID.|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
import wantAgent from '@ohos.wantAgent';
// WantAgentInfo object
let wantAgentInfo = {
wants: [
{
deviceId: "deviceId",
bundleName: "com.neu.setResultOnAbilityResultTest1",
abilityName: "com.example.test.MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters:
{
mykey0: 2222,
mykey1: [1, 2, 3],
mykey2: "[1, 2, 3]",
mykey3: "ssssssssssssssssssssssssss",
mykey4: [false, true, false],
mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"],
mykey6: true,
}
}
],
operationType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}
wantAgent.getWantAgent(wantAgentInfo).then((agent) => {
session.setLaunchAbility(agent, function (err) {
if (err) {
console.info(`SetLaunchAbility BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('SetLaunchAbility successfully');
}
});
});
```
### getController
getController(): Promise\<AVSessionController>
Obtains the controller corresponding to this session. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| ---------------------------------------------------- | ----------------------------- |
| Promise<[AVSessionController](#avsessioncontroller)> | Promise used to return the session controller.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
let controller;
session.getController().then((avcontroller) => {
controller = avcontroller;
console.info(`GetController : SUCCESS : sessionid : ${controller.sessionId}`);
}).catch((err) => {
console.info(`GetController BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### getController
getController(callback: AsyncCallback\<AVSessionController>): void
Obtains the controller corresponding to this session. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------------- | ---- | -------------------------- |
| callback | AsyncCallback<[AVSessionController](#avsessioncontroller)\> | Yes | Callback used to return the session controller.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
let controller;
session.getController(function (err, avcontroller) {
if (err) {
console.info(`GetController BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
controller = avcontroller;
console.info(`GetController : SUCCESS : sessionid : ${controller.sessionId}`);
}
});
```
### getOutputDevice
getOutputDevice(): Promise\<OutputDeviceInfo>
Obtains information about the output device for this session. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| ---------------------------------------------- | --------------------------------- |
| Promise<[OutputDeviceInfo](#outputdeviceinfo)> | Promise used to return the output device information.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.getOutputDevice().then((outputDeviceInfo) => {
console.info(`GetOutputDevice : SUCCESS : isRemote : ${outputDeviceInfo.isRemote}`);
}).catch((err) => {
console.info(`GetOutputDevice BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### getOutputDevice
getOutputDevice(callback: AsyncCallback\<OutputDeviceInfo>): void
Obtains information about the output device for this session. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | Yes | Callback used to return the information obtained.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.getOutputDevice(function (err, outputDeviceInfo) {
if (err) {
console.info(`GetOutputDevice BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info(`GetOutputDevice : SUCCESS : isRemote : ${outputDeviceInfo.isRemote}`);
}
});
```
### activate
activate(): Promise\<void>
Activates this session. A session can be used only after being activated. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the session is activated, no value is returned; otherwise, an error object is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.activate().then(() => {
console.info('Activate : SUCCESS ');
}).catch((err) => {
console.info(`Activate BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### activate
activate(callback: AsyncCallback\<void>): void
Activates this session. A session can be used only after being activated. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the session is activated, **err** is **undefined**; otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.activate(function (err) {
if (err) {
console.info(`Activate BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('Activate : SUCCESS ');
}
});
```
### deactivate
deactivate(): Promise\<void>
Deactivates this session. You can use [activate](#activate) to activate the session again. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the session is deactivated, no value is returned; otherwise, an error object is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.deactivate().then(() => {
console.info('Deactivate : SUCCESS ');
}).catch((err) => {
console.info(`Deactivate BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### deactivate
deactivate(callback: AsyncCallback\<void>): void
Deactivates this session. This API uses an asynchronous callback to return the result.
Deactivates this session. You can use [activate](#activate) to activate the session again.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the session is deactivated, **err** is **undefined**; otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.deactivate(function (err) {
if (err) {
console.info(`Deactivate BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('Deactivate : SUCCESS ');
}
});
```
### destroy
destroy(): Promise\<void>
Destroys this session. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the session is destroyed, no value is returned; otherwise, an error object is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.destroy().then(() => {
console.info('Destroy : SUCCESS ');
}).catch((err) => {
console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### destroy
destroy(callback: AsyncCallback\<void>): void
Destroys this session. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the session is destroyed, **err** is **undefined**; otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.destroy(function (err) {
if (err) {
console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('Destroy : SUCCESS ');
}
});
```
### on('play'|'pause'|'stop'|'playNext'|'playPrevious'|'fastForward'|'rewind')
on(type: 'play'|'pause'|'stop'|'playNext'|'playPrevious'|'fastForward'|'rewind', callback: () => void): void
Subscribes to playback command events.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The following events are supported: **'play'**, **'pause'**, **'stop'**, **'playNext'**, **'playPrevious'**, **'fastForward'**, and **'rewind'**.<br>The event is reported when the corresponding playback command is sent to the session.|
| callback | callback: () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.on('play', () => {
console.info('on play entry');
});
session.on('pause', () => {
console.info('on pause entry');
});
session.on('stop', () => {
console.info('on stop entry');
});
session.on('playNext', () => {
console.info('on playNext entry');
});
session.on('playPrevious', () => {
console.info('on playPrevious entry');
});
session.on('fastForward', () => {
console.info('on fastForward entry');
});
session.on('rewind', () => {
console.info('on rewind entry');
});
```
### on('seek')
on(type: 'seek', callback: (time: number) => void): void
Subscribes to the seek event.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'seek'** is reported when the seek command is sent to the session.|
| callback | (time: number) => void | Yes | Callback used for subscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
The session does not exist
```js
session.on('seek', (time) => {
console.info(`on seek entry time : ${time}`);
});
```
### on('setSpeed')
on(type: 'setSpeed', callback: (speed: number) => void): void
Subscribes to the event for setting the playback speed.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'setSpeed'** is reported when the command for setting the playback speed is sent to the session.|
| callback | (speed: number) => void | Yes | Callback used for subscription. The **speed** parameter in the callback indicates the playback speed. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.on('setSpeed', (speed) => {
console.info(`on setSpeed speed : ${speed}`);
});
```
### on('setLoopMode')
on(type: 'setLoopMode', callback: (mode: LoopMode) => void): void
Subscribes to the event for setting the loop mode.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---- |
| type | string | Yes | Event type. The event **'setLoopMode'** is reported when the command for setting the loop mode is sent to the session.|
| callback | (mode: [LoopMode](#loopmode)) => void | Yes | Callback used for subscription. The **mode** parameter in the callback indicates the loop mode. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.on('setLoopMode', (mode) => {
console.info(`on setLoopMode mode : ${mode}`);
});
```
### on('toggleFavorite')
on(type: 'toggleFavorite', callback: (assetId: string) => void): void
Subscribes to the event for favoriting a media asset.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'toggleFavorite'** is reported when the command for favoriting the media asset is sent to the session.|
| callback | (assetId: string) => void | Yes | Callback used for subscription. The **assetId** parameter in the callback indicates the media asset ID. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.on('toggleFavorite', (assetId) => {
console.info(`on toggleFavorite mode : ${assetId}`);
});
```
### on('handleKeyEvent')
on(type: 'handleKeyEvent', callback: (event: KeyEvent) => void): void
Subscribes to the key event.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'handleKeyEvent'** is reported when a key event is sent to the session.|
| callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | Yes | Callback used for subscription. The **event** parameter in the callback indicates the key event. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.on('handleKeyEvent', (event) => {
console.info(`on handleKeyEvent event : ${event}`);
});
```
### on('outputDeviceChange')
on(type: 'outputDeviceChange', callback: (device: OutputDeviceInfo) => void): void
Subscribes to output device changes.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'outputDeviceChange'** is reported when the output device changes.|
| callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | Yes | Callback used for subscription. The **device** parameter in the callback indicates the output device information. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.on('outputDeviceChange', (device) => {
console.info(`on outputDeviceChange device isRemote : ${device.isRemote}`);
});
```
### off('play'|'pause'|'stop'|'playNext'|'playPrevious'|'fastForward'|'rewind')
off(type: 'play' | 'pause' | 'stop' | 'playNext' | 'playPrevious' | 'fastForward' | 'rewind', callback?: () => void): void
Unsubscribes from playback command events.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- |
| type | string | Yes | Event type. The following events are supported: **'play'**, **'pause'**, **'stop'**, **'playNext'**, **'playPrevious'**, **'fastForward'**, and **'rewind'**.|
| callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.off('play');
session.off('pause');
session.off('stop');
session.off('playNext');
session.off('playPrevious');
session.off('fastForward');
session.off('rewind');
```
### off('seek')
off(type: 'seek', callback?: (time: number) => void): void
Unsubscribes from the seek event.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ----------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'seek'**. |
| callback | (time: number) => void | No | Callback used for unsubscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.off('seek');
```
### off('setSpeed')
off(type: 'setSpeed', callback?: (speed: number) => void): void
Unsubscribes from the event for setting the playback speed.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------------|
| type | string | Yes | Event type. The value is fixed at **'setSpeed'**. |
| callback | (speed: number) => void | No | Callback used for unsubscription. The **speed** parameter in the callback indicates the playback speed.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.off('setSpeed');
```
### off('setLoopMode')
off(type: 'setLoopMode', callback?: (mode: LoopMode) => void): void
Unsubscribes from the event for setting loop mode.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ----- |
| type | string | Yes | Event type. The value is fixed at **'setLoopMode'**.|
| callback | (mode: [LoopMode](#loopmode)) => void | No | Callback used for unsubscription. The **mode** parameter in the callback indicates the loop mode.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.off('setLoopMode');
```
### off('toggleFavorite')
off(type: 'toggleFavorite', callback?: (assetId: string) => void): void
Unsubscribes from the event for favoriting a media asset.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | -------------------------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'toggleFavorite'**. |
| callback | (assetId: string) => void | No | Callback used for unsubscription. The **assetId** parameter in the callback indicates the media asset ID.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.off('toggleFavorite');
```
### off('handleKeyEvent')
off(type: 'handleKeyEvent', callback?: (event: KeyEvent) => void): void
Unsubscribes from the key event.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **'handleKeyEvent'**. |
| callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | No | Callback used for unsubscription. The **event** parameter in the callback indicates the key event.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.off('handleKeyEvent');
```
### off('outputDeviceChange')
off(type: 'outputDeviceChange', callback?: (device: OutputDeviceInfo) => void): void
Unsubscribes from playback device changes.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **'outputDeviceChange'**. |
| callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
**Example**
```js
session.off('outputDeviceChange');
```
## AVSessionController<a name="section974602"></a>
An AV session controller is created by calling [avSession.createController](#avsessioncreatecontroller). Through the AV session controller, you can query the session ID, send commands and events to a session, and obtain session metadata and playback state information.
### Attributes
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Type | Readable| Writable| Description |
| :-------- | :----- | :--- | :--- | :-------------------------------------- |
| sessionId | string | Yes | No | Unique session ID of the **AVSessionController** object.|
**Example**
```js
let sessionId;
await avSession.createController(session.sessionId).then((controller) => {
sessionId = controller.sessionId;
}).catch((err) => {
console.info(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### getAVPlaybackState
getAVPlaybackState(): Promise\<AVPlaybackState>
Obtains the information related to the playback state. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| --------------------------------------------- | --------------------------- |
| Promise<[AVPlaybackState](#avplaybackstate)\> | Promise used to return the **AVPlaybackState** object.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.getAVPlaybackState().then((playbackState) => {
console.info(`GetAVPlaybackState : SUCCESS : state : ${playbackState.state}`);
}).catch((err) => {
console.info(`GetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### getAVPlaybackState
getAVPlaybackState(callback: AsyncCallback\<AVPlaybackState>): void
Obtains the information related to the playback state. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | ---------------------------- |
| callback | AsyncCallback<[AVPlaybackState](#avplaybackstate)\> | Yes | Callback used to return the **AVPlaybackState** object.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.getAVPlaybackState(function (err, playbackState) {
if (err) {
console.info(`GetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info(`GetAVPlaybackState : SUCCESS : state : ${playbackState.state}`);
}
});
```
### getAVMetadata
getAVMetadata(): Promise\<AVMetadata>
Obtains the session metadata. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| ----------------------------------- | ----------------------------- |
| Promise<[AVMetadata](#avmetadata)\> | Promise used to return the metadata obtained.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.getAVMetadata().then((metadata) => {
console.info(`GetAVMetadata : SUCCESS : assetId : ${metadata.assetId}`);
}).catch((err) => {
console.info(`GetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### getAVMetadata
getAVMetadata(callback: AsyncCallback\<AVMetadata>): void
Obtains the session metadata. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | -------------------------- |
| callback | AsyncCallback<[AVMetadata](#avmetadata)\> | Yes | Callback used to return the metadata obtained.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.getAVMetadata(function (err, metadata) {
if (err) {
console.info(`GetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info(`GetAVMetadata : SUCCESS : assetId : ${metadata.assetId}`);
}
});
```
### getOutputDevice
getOutputDevice(): Promise\<OutputDeviceInfo>
Obtains the output device information. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| ----------------------------------------------- | --------------------------------- |
| Promise<[OutputDeviceInfo](#outputdeviceinfo)\> | Promise used to return the information obtained.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.getOutputDevice().then((deviceInfo) => {
console.info(`GetOutputDevice : SUCCESS : isRemote : ${deviceInfo.isRemote}`);
}).catch((err) => {
console.info(`GetOutputDevice BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### getOutputDevice
getOutputDevice(callback: AsyncCallback\<OutputDeviceInfo>): void
Obtains the output device information. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | Yes | Callback used to return the information obtained.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.getOutputDevice(function (err, deviceInfo) {
if (err) {
console.info(`GetOutputDevice BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info(`GetOutputDevice : SUCCESS : isRemote : ${deviceInfo.isRemote}`);
}
});
```
### sendAVKeyEvent
sendAVKeyEvent(event: KeyEvent): Promise\<void>
Sends a key event to the session corresponding to this controller. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------------------------------------ | ---- | ---------- |
| event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
| 6600105 | Invalid session command |
| 6600106 | The session not active |
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.|
**Example**
```js
let keyItem = {code:0x49, pressedTime:2, deviceId:0};
let event = {action:2, key:keyItem, keys:[keyItem]};
controller.sendAVKeyEvent(event).then(() => {
console.info('SendAVKeyEvent Successfully');
}).catch((err) => {
console.info(`SendAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### sendAVKeyEvent
sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback\<void>): void
Sends a key event to the session corresponding to this controller. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ---------- |
| event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event.|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
| 6600105 | Invalid session command |
| 6600106 | The session not active |
**Example**
```js
let keyItem = {code:0x49, pressedTime:2, deviceId:0};
let event = {action:2, key:keyItem, keys:[keyItem]};
controller.sendAVKeyEvent(event, function (err) {
if (err) {
console.info(`SendAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('SendAVKeyEvent Successfully');
}
});
```
### getLaunchAbility
getLaunchAbility(): Promise\<WantAgent>
Obtains the **WantAgent** object saved by the application in the session. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| ------------------------------------------- | ------------------------------------------------------------ |
| Promise<[WantAgent](js-apis-wantAgent.md)\> | Promise used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
**Example**
```js
import wantAgent from '@ohos.wantAgent';
controller.getLaunchAbility().then((agent) => {
console.info(`GetLaunchAbility : SUCCESS : wantAgent : ${agent}`);
}).catch((err) => {
console.info(`GetLaunchAbility BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### getLaunchAbility
getLaunchAbility(callback: AsyncCallback\<WantAgent>): void
Obtains the **WantAgent** object saved by the application in the session. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback<[WantAgent](js-apis-wantAgent.md)\> | Yes | Callback used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
**Example**
```js
import wantAgent from '@ohos.wantAgent';
controller.getLaunchAbility(function (err, agent) {
if (err) {
console.info(`GetLaunchAbility BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info(`GetLaunchAbility : SUCCESS : wantAgent : ${agent}`);
}
});
```
### getRealPlaybackPositionSync
getRealPlaybackPositionSync(): number
Obtains the playback position.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| ------ | ------------------ |
| number | Playback position, in milliseconds.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600103 | The session controller does not exist |
**Example**
```js
let time = controller.getRealPlaybackPositionSync();
```
### isActive
isActive(): Promise\<boolean>
Checks whether the session is activated. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| ----------------- | ------------------------------------------------------------ |
| Promise<boolean\> | Promise used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.isActive().then((isActive) => {
console.info(`IsActive : SUCCESS : isactive : ${isActive}`);
}).catch((err) => {
console.info(`IsActive BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### isActive
isActive(callback: AsyncCallback\<boolean>): void
Checks whether the session is activated. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback<boolean\> | Yes | Callback used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.isActive(function (err, isActive) {
if (err) {
console.info(`IsActive BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info(`IsActive : SUCCESS : isactive : ${isActive}`);
}
});
```
### destroy
destroy(): Promise\<void>
Destroys this controller. A controller can no longer be used after being destroyed. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the controller is destroyed, no value is returned; otherwise, an error object is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.destroy().then(() => {
console.info('Destroy : SUCCESS ');
}).catch((err) => {
console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### destroy
destroy(callback: AsyncCallback\<void>): void
Destroys this controller. A controller can no longer be used after being destroyed. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the controller is destroyed, **err** is **undefined**; otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.destroy(function (err) {
if (err) {
console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('Destroy : SUCCESS ');
}
});
```
### getValidCommands
getValidCommands(): Promise\<Array\<AVControlCommandType>>
Obtains valid commands supported by the session. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Return value**
| Type | Description |
| ------------------------------------------------------------ | --------------------------------- |
| Promise<Array<[AVControlCommandType](#avcontrolcommandtype)\>\> | Promise used to return a set of valid commands.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.getValidCommands.then((validCommands) => {
console.info(`GetValidCommands : SUCCESS : size : ${validCommands.length}`);
}).catch((err) => {
console.info(`GetValidCommands BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### getValidCommands
getValidCommands(callback: AsyncCallback\<Array\<AVControlCommandType>>): void
Obtains valid commands supported by the session. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------ |
| callback | AsyncCallback\<Array\<[AVControlCommandType](#avcontrolcommandtype)\>\> | Yes | Callback used to return a set of valid commands.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.getValidCommands(function (err, validCommands) {
if (err) {
console.info(`GetValidCommands BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info(`GetValidCommands : SUCCESS : size : ${validCommands.length}`);
}
});
```
### sendControlCommand
sendControlCommand(command: AVControlCommand): Promise\<void>
Sends a control command to the session through the controller. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ------------------------------ |
| command | [AVControlCommand](#avcontrolcommand) | Yes | Command to send.|
**Return value**
| Type | Description |
| -------------- | ----------------------------- |
| Promise<void\> | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.|
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
| 6600105 | Invalid session command |
| 6600106 | The session not active |
| 6600107 | Command or event overload |
**Example**
```js
let avCommand = {command:'play'};
// let avCommand = {command:'pause'};
// let avCommand = {command:'stop'};
// let avCommand = {command:'playNext'};
// let avCommand = {command:'playPrevious'};
// let avCommand = {command:'fastForward'};
// let avCommand = {command:'rewind'};
// let avCommand = {command:'seek', parameter:10};
// let avCommand = {command:'setSpeed', parameter:2.6};
// let avCommand = {command:'setLoopMode', parameter:avSession.LoopMode.LOOP_MODE_SINGLE};
// let avCommand = {command:'toggleFavorite', parameter:"false"};
controller.sendControlCommand(avCommand).then(() => {
console.info('SendControlCommand successfully');
}).catch((err) => {
console.info(`SendControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
});
```
### sendControlCommand
sendControlCommand(command: AVControlCommand, callback: AsyncCallback\<void>): void
Sends a control command to the session through the controller. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ------------------------------ |
| command | [AVControlCommand](#avcontrolcommand) | Yes | Command to send.|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ------------------------------- |
| 6600101 | Session service exception |
| 6600102 | The session does not exist |
| 6600103 | The session controller does not exist |
| 6600105 | Invalid session command |
| 6600106 | The session not active |
| 6600107 | Command or event overload |
**Example**
```js
let avCommand = {command:'play'};
// let avCommand = {command:'pause'};
// let avCommand = {command:'stop'};
// let avCommand = {command:'playNext'};
// let avCommand = {command:'playPrevious'};
// let avCommand = {command:'fastForward'};
// let avCommand = {command:'rewind'};
// let avCommand = {command:'seek', parameter:10};
// let avCommand = {command:'setSpeed', parameter:2.6};
// let avCommand = {command:'setLoopMode', parameter:avSession.LoopMode.LOOP_MODE_SINGLE};
// let avCommand = {command:'toggleFavorite', parameter:"false"};
controller.sendControlCommand(avCommand, function (err) {
if (err) {
console.info(`SendControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
} else {
console.info('SendControlCommand successfully');
}
});
```
### on('metadataChange')
on(type: 'metadataChange', filter: Array\<keyof AVMetadata> | 'all', callback: (data: AVMetadata) => void)
Subscribes to the metadata change event.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'metadataChange'** is reported when the session metadata changes.|
| filter | Array\<keyof&nbsp;[AVMetadata](#avmetadata)\>&nbsp;&#124;&nbsp;'all' | Yes | The value **'all'** indicates that any metadata field change will trigger the event, and **Array<keyof [AVMetadata](#avmetadata)\>** indicates that only changes to the listed metadata field will trigger the event.|
| callback | (data: [AVMetadata](#avmetadata)) => void | Yes | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ------------------------------ |
| 6600101 | Session service exception |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.on('metadataChange', 'all', (metadata) => {
console.info(`on metadataChange assetId : ${metadata.assetId}`);
});
let metaFilter = ['assetId', 'title', 'description'];
controller.on('metadataChange', metaFilter, (metadata) => {
console.info(`on metadataChange assetId : ${metadata.assetId}`);
});
```
### on('playbackStateChange')
on(type: 'playbackStateChange', filter: Array\<keyof AVPlaybackState> | 'all', callback: (state: AVPlaybackState) => void)
Subscribes to the playback state change event.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'playbackStateChange'** is reported when the playback state changes.|
| filter | Array\<keyof&nbsp;[AVPlaybackState](#avplaybackstate)\>&nbsp;&#124;&nbsp;'all' | Yes | The value **'all'** indicates that any playback state field change will trigger the event, and **Array<keyof [AVPlaybackState](#avplaybackstate)\>** indicates that only changes to the listed playback state field will trigger the event.|
| callback | (state: [AVPlaybackState](#avplaybackstate)) => void | Yes | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ------------------------------ |
| 6600101 | Session service exception |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.on('playbackStateChange', 'all', (playbackState) => {
console.info(`on playbackStateChange state : ${playbackState.state}`);
});
let playbackFilter = ['state', 'speed', 'loopMode'];
controller.on('playbackStateChange', playbackFilter, (playbackState) => {
console.info(`on playbackStateChange state : ${playbackState.state}`);
});
```
### on('sessionDestroy')
on(type: 'sessionDestroy', callback: () => void)
Subscribes to the session destruction event.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'sessionDestroy'** is reported when the session is destroyed.|
| callback | () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ------------------------------ |
| 6600101 | Session service exception |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.on('sessionDestroy', () => {
console.info('on sessionDestroy : SUCCESS ');
});
```
### on('activeStateChange')
on(type: 'activeStateChange', callback: (isActive: boolean) => void)
Subscribes to the session activation state change event.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'activeStateChange'** is reported when the activation state of the session changes.|
| callback | (isActive: boolean) => void | Yes | Callback used for subscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the service is activated, and **false** means the opposite. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ----------------------------- |
| 6600101 | Session service exception |
| 6600103 |The session controller does not exist |
**Example**
```js
controller.on('activeStateChange', (isActive) => {
console.info(`on activeStateChange : SUCCESS : isActive ${isActive}`);
});
```
### on('validCommandChange')
on(type: 'validCommandChange', callback: (commands: Array\<AVControlCommandType>) => void)
Subscribes to valid command changes.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'validCommandChange'** is reported when the valid commands supported by the session changes.|
| callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | Yes | Callback used for subscription. The **commands** parameter in the callback is a set of valid commands. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ------------------------------ |
| 6600101 | Session service exception |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.on('validCommandChange', (validCommands) => {
console.info(`validCommandChange : SUCCESS : size : ${validCommands.size}`);
console.info(`validCommandChange : SUCCESS : validCommands : ${validCommands.values()}`);
});
```
### on('outputDeviceChange')
on(type: 'outputDeviceChange', callback: (device: OutputDeviceInfo) => void): void
Subscribes to output device changes.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The event **'outputDeviceChange'** is reported when the output device changes.|
| callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | Yes | Callback used for subscription. The **device** parameter in the callback indicates the output device information. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ----------------------- |
| 6600101 | Session service exception |
| 6600103 | The session controller does not exist |
**Example**
```js
controller.on('outputDeviceChange', (device) => {
console.info(`on outputDeviceChange device isRemote : ${device.isRemote}`);
});
```
### off('metadataChange')
off(type: 'metadataChange', callback?: (data: AVMetadata) => void)
Unsubscribes from metadata changes.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------ |
| type | string | Yes | Event type. The event **'metadataChange'** is reported when the session metadata changes. |
| callback | (data: [AVMetadata](#avmetadata)) => void | No | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------- |
| 6600101 | Session service exception |
**Example**
```js
controller.off('metadataChange');
```
### off('playbackStateChange')
off(type: 'playbackStateChange', callback?: (state: AVPlaybackState) => void)
Unsubscribes from playback state changes.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
| type | string | Yes | Event type. The event **'playbackStateChange'** is reported when the playback state changes. |
| callback | (state: [AVPlaybackState](#avplaybackstate)) => void | No | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------- |
| 6600101 | Session service exception |
**Example**
```js
controller.off('playbackStateChange');
```
### off('sessionDestroy')
off(type: 'sessionDestroy', callback?: () => void)
Unsubscribes from the session destruction event.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------- | ---- | ----------------------------------------------------- |
| type | string | Yes | Event type. The event **'sessionDestroy'** is reported when the session is destroyed. |
| callback | () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------- |
| 6600101 | Session service exception |
**Example**
```js
controller.off('sessionDestroy');
```
### off('activeStateChange')
off(type: 'activeStateChange', callback?: (isActive: boolean) => void)
Unsubscribes from session activation state changes.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ----------------------------------------------------- |
| type | string | Yes | Event type. The event **'activeStateChange'** is reported when the session activation state changes. |
| callback | (isActive: boolean) => void | No | Callback used for unsubscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the session is activated, and **false** means the opposite.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message|
| -------- | ---------------- |
| 6600101 | Session service exception |
**Example**
```js
controller.off('activeStateChange');
```
### off('validCommandChange')
off(type: 'validCommandChange', callback?: (commands: Array\<AVControlCommandType>) => void)
Unsubscribes from valid command changes.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- |
| type | string | Yes | Event type. The event **'validCommandChange'** is reported when the supported commands change. |
| callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | No | Callback used for unsubscription. The **commands** parameter in the command is a set of valid commands.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID| Error Message |
| -------- | ---------------- |
| 6600101 | Session service exception |
**Example**
```js
controller.off('validCommandChange');
```
### off('outputDeviceChange')
off(type: 'outputDeviceChange', callback?: (device: OutputDeviceInfo) => void): void
Unsubscribes from output device changes.
**System capability**: SystemCapability.Multimedia.AVSession.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------ |
| type | string | Yes | Event type. The event **'outputDeviceChange'** is reported when the output device changes. |
| callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.<br>The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. |
**Error codes**
For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
| ID | Error Message |
| -------- | ---------------- |
| 6600101 | Session service exception |
**Example**
```js
controller.off('outputDeviceChange');
```
## SessionToken
Describes the information about a session token.
**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
| Name | Type | Mandatory| Description |
| :-------- | :----- | :--- | :----------- |
| sessionId | string | Yes | Session ID. |
| pid | number | Yes | Process ID of the session.|
| uid | number | Yes | User ID. |
## AVSessionType
Enumerates the session types supported by the session.
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Type | Description|
| ----- | ------ | ---- |
| audio | string | Audio session.|
| video | string | Video session.|
## AVSessionDescriptor
Declares the session descriptor.
**System capability**: SystemCapability.Multimedia.AVSession.Manager
**System API**: This is a system API.
| Name | Type | Readable| Writable| Description |
| ------------ | ------------------------------------------------------------ | ---- | --------------------------------------------------- | --------------------------------------------------- |
| sessionId | string | Yes | No| Session ID. |
| type | [AVSessionType](#avsessiontype) | Yes | No | Session type. |
| sessionTag | string | Yes | No | Custom session name. |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Information about the application to which the session belongs, including the bundle name and ability name.|
| isActive | boolean | Yes | No | Whether the session is activated. |
| isTopSession | boolean | Yes | No | Whether the session is the top session. |
| outputDevice | [OutputDeviceInfo](#outputdeviceinfo) | Yes | No | Information about the output device. |
## AVControlCommandType
Enumerates the commands that can be sent to a session.
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Type | Description |
| -------------- | ------ | ------------ |
| play | string | Play the media. |
| pause | string | Pause the playback. |
| stop | string | Stop the playback. |
| playNext | string | Play the next media asset. |
| playPrevious | string | Play the previous media asset. |
| fastForward | string | Fast-forward. |
| rewind | string | Rewind. |
| seek | string | Seek to a playback position.|
| setSpeed | string | Set the playback speed.|
| setLoopMode | string | Set the loop mode.|
| toggleFavorite | string | Favorite the media asset. |
## AVControlCommand
Describes the command that can be sent to the session.
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------- | ---- | -------------- |
| command | [AVControlCommandType](#avcontrolcommandtype) | Yes | Command. |
| parameter | [LoopMode](#loopmode) &#124; string &#124; number | No | Parameters carried in the command.|
## AVMetadata
Describes the media metadata.
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Type | Mandatory| Description |
| --------------- |-------------------------| ---- |---------------------------------------------------------------------|
| assetId | string | Yes | Media ID. |
| title | string | No | Title. |
| artist | string | No | Artist. |
| author | string | No | Author. |
| album | string | No | Album name. |
| writer | string | No | Writer. |
| composer | string | No | composer. |
| duration | string | No | Media duration, in ms. |
| mediaImage | image.PixelMap &#124; string | No | Pixel map or image path (local path or network path) of the image. |
| publishDate | Date | No | Release date. |
| subtitle | string | No | Subtitle. |
| description | string | No | Media description. |
| lyric | string | No | Lyric file path (local path or network path).|
| previousAssetId | string | No | ID of the previous media asset. |
| nextAssetId | string | No | ID of the next media asset. |
## AVPlaybackState
Describes the information related to the media playback state.
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Type | Mandatory| Description |
| ------------ | ------------------------------------- | ---- | ------- |
| state | [PlaybackState](#playbackstate) | No | Playback state.|
| speed | number | No | Playback speed.|
| position | [PlaybackPosition](#playbackposition) | No | Playback position.|
| bufferedTime | number | No | Buffered time.|
| loopMode | [LoopMode](#loopmode) | No | Loop mode.|
| isFavorite | boolean | No | Whether the media asset is favorited.|
## PlaybackPosition
Describes the information related to the playback position.
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Type | Mandatory| Description |
| ----------- | ------ | ---- | ------------------ |
| elapsedTime | number | Yes | Elapsed time, in ms.|
| updateTime | number | Yes | Updated time, in ms.|
## OutputDeviceInfo
Describes the information related to the output device.
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Type | Mandatory| Description |
| ---------- | -------------- | ---- | ---------------------- |
| isRemote | boolean | Yes | Whether the device is connected. |
| audioDeviceId | Array<number\> | Yes | IDs of output devices. |
| deviceName | Array<string\> | Yes | Names of output devices. |
## PlaybackState
Enumerates the media playback states.
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Value | Description |
| --------------------------- | ---- | ----------- |
| PLAYBACK_STATE_INITIAL | 0 | Initial. |
| PLAYBACK_STATE_PREPARE | 1 | Preparing. |
| PLAYBACK_STATE_PLAY | 2 | Playing. |
| PLAYBACK_STATE_PAUSE | 3 | Paused. |
| PLAYBACK_STATE_FAST_FORWARD | 4 | Fast-forwarding. |
| PLAYBACK_STATE_REWIND | 5 | Rewinding. |
| PLAYBACK_STATE_STOP | 6 | Stopped. |
## LoopMode
Enumerates the loop modes of media playback.
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Value | Description |
| ------------------ | ---- | -------- |
| LOOP_MODE_SEQUENCE | 0 | Sequential playback.|
| LOOP_MODE_SINGLE | 1 | Single loop.|
| LOOP_MODE_LIST | 2 | Playlist loop.|
| LOOP_MODE_SHUFFLE | 3 | Shuffle.|
## AVSessionErrorCode
Enumerates the error codes used in the media session.
**System capability**: SystemCapability.Multimedia.AVSession.Core
| Name | Value | Description |
| ------------------------------ | ------- | ------------------------------- |
| ERR_CODE_SERVICE_EXCEPTION | 6600101 | Session service exception |
| ERR_CODE_SESSION_NOT_EXIST | 6600102 | The session does not exist |
| ERR_CODE_CONTROLLER_NOT_EXIST | 6600103 | The session controller does not exist |
| ERR_CODE_REMOTE_CONNECTION_ERR | 6600104 | The remote session connection failed |
| ERR_CODE_COMMAND_INVALID | 6600105 | Invalid session command |
| ERR_CODE_SESSION_INACTIVE | 6600106 | The session not active |
| ERR_CODE_MESSAGE_OVERLOAD | 6600107 | Command or event overload |
# AVSession Management Error Codes
## 6600101 Session Service Exception
**Error Message**
Session service exception
**Description**
The session service is abnormal, and the application cannot obtain a response from the session service. For example, the session service is not running or the communication with the session service fails.
**Possible Causes**
The session service is killed during session restart.
**Solution**
1. The system retries the operation automatically. If the error persists for 3 seconds or more, stop the operation on the session or controller.
2. Destroy the current session or session controller and re-create it. If the re-creation fails, stop the operation on the session.
## 6600102 Session Does Not Exist
**Error Message**
The session does not exist
**Description**
Parameters are set for or commands are sent to the session that does not exist.
**Possible Causes**
The session has been destroyed, and no session record exists on the server.
**Solution**
1. If the error occurs on the application, re-create the session. If the error occurs on Media Controller, stop sending query or control commands to the session.
2. If the error occurs on the session service, query the current session record and pass the correct session ID when creating the controller.
## 6600103 Session Controller Does Not Exist
**Error Message**
The session controller does not exist
**Description**
A control command or an event is sent to the controller that does not exist.
**Possible Causes**
The controller has been destroyed.
**Solution**
Query the session record and create the corresponding controller.
## 6600104 Remote Session Connection Failure
**Error Message**
The remote session connection failed
**Description**
The communication between the local session and the remote session fails.
**Possible Causes**
The communication between devices is interrupted.
**Solution**
Stop sending control commands to the session. Subscribe to output device changes, and resume the sending when the output device is changed.
## 6600105 Invalid Session Command
**Error Message**
Invalid session command
**Description**
The control command or event sent to the session is not supported.
**Possible Causes**
The session does not support this command.
**Solution**
Stop sending the command or event. Query the commands supported by the session, and send a command supported.
## 6600106 Session Not Activated
**Error Message**
The session not active
**Description**
A control command or event is sent to the session that is not activated.
**Possible Causes**
The session is in the inactive state.
**Solution**
Stop sending the command or event. Subscribe to the session activation status, and resume the sending when the session is activated.
## 6600107 Too Many Commands or Events
**Error Message**
Command or event overload
**Description**
The session client sends too many messages or commands to the server in a period of time, causing the server to be overloaded.
**Possible Causes**
The server is overloaded with messages or events.
**Solution**
Control the frequency of sending commands or events.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册