Interface (AVSessionController)

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.

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.
  • The initial APIs of this interface are supported since API version 10.

Modules to Import

import { avSession } from '@kit.AVSessionKit';

Properties

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Name Type Read-Only Optional Description
sessionId10+ string Yes No Unique session ID of the AVSessionController object.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  private tag: string = "createNewSession";
  private sessionId: string = "";
  private AVSessionController?: avSession.AVSessionController;
  private currentAVSession?: avSession.AVSession;
  context = this.getUIContext();

  aboutToAppear(): void {

    avSession.createAVSession(this.getUIContext().getHostContext(), this.tag, "audio").then(async (data: avSession.AVSession) => {
      this.currentAVSession = data;
      this.sessionId = this.currentAVSession.sessionId;
      this.AVSessionController = await this.currentAVSession.getController();
      console.info(`Succeeded in creating AV session, sessionId: ${this.sessionId}`);
    });
  }

  build() {
    Column() {
      Text('AVSession Demo')
        .fontSize(20)
        .margin(10)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

getAVPlaybackState10+

getAVPlaybackState(callback: AsyncCallback<AVPlaybackState>): void

Obtains the remote 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> Yes Callback used to return the remote playback state.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

avsessionController.getAVPlaybackState((state: avSession.AVPlaybackState) => {
  console.info('Succeeded in getting AV playback state.');
});

getAVPlaybackState10+

getAVPlaybackState(): Promise<AVPlaybackState>

Obtains the remote playback state. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<AVPlaybackState> Promise used to return the remote playback status.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

avsessionController.getAVPlaybackState().then((state: avSession.AVPlaybackState) => {
  console.info('Succeeded in getting AV playback state.');
});

getAVMetadata10+

getAVMetadata(): Promise<AVMetadata>

Obtains the session metadata. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<AVMetadata> Promise used to return the metadata obtained.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

avsessionController.getAVMetadata().then((metadata: avSession.AVMetadata) => {
  console.info(`Succeeded in getting AV metadata, assetId: ${metadata.assetId}`);
});

getAVMetadata10+

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> Yes Callback used to return the metadata obtained.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

avsessionController.getAVMetadata((metadata: avSession.AVMetadata) => {
  console.info(`Succeeded in getting AV metadata, assetId: ${metadata.assetId}`);
});

getAVQueueTitle10+

getAVQueueTitle(): Promise<string>

Obtains the name of the playlist. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<string> Promise used to return the playlist name.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


avsessionController.getAVQueueTitle().then((title: string) => {
  console.info(`Succeeded in getting AV queue title: ${title}`);
});

getAVQueueTitle10+

getAVQueueTitle(callback: AsyncCallback<string>): void

Obtains the name of the playlist. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
callback AsyncCallback<string> Yes Callback used to return the playlist name.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


avsessionController.getAVQueueTitle((title: string) => {
  console.info(`Succeeded in getting AV queue title: ${title}`);
});

getAVQueueItems10+

getAVQueueItems(): Promise<Array<AVQueueItem>>

Obtains the information related to the items in the queue. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<Array<AVQueueItem>> Promise used to return the items in the queue.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


avsessionController.getAVQueueItems().then((items: avSession.AVQueueItem[]) => {
  console.info(`Succeeded in getting AV queue items, length: ${items.length}`);
});

getAVQueueItems10+

getAVQueueItems(callback: AsyncCallback<Array<AVQueueItem>>): void

Obtains the information related to the items in the playlist. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
callback AsyncCallback<Array<AVQueueItem>> Yes Callback used to return the items in the playlist.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


avsessionController.getAVQueueItems((items: avSession.AVQueueItem[]) => {
  console.info(`Succeeded in getting AV queue items, length: ${items.length}`);
});

skipToQueueItem10+

skipToQueueItem(itemId: number): Promise<void>

Sends the ID of an item in the playlist to the session for processing. The session can play the song. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
itemId number Yes ID of an item in the playlist.

Return value

Type Description
Promise<void> Promise used to return the result. If the item ID is sent, no value is returned; otherwise, an error object is returned.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed.
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


let queueItemId = 0;
avsessionController.skipToQueueItem(queueItemId).then(() => {
  console.info('Succeeded in skipping to queue item.');
});

skipToQueueItem10+

skipToQueueItem(itemId: number, callback: AsyncCallback<void>): void

Sends the ID of an item in the playlist to the session for processing. The session can play the song. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
itemId number Yes ID of an item in the playlist.
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 Universal Error Codes and AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed.
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


let queueItemId = 0;
avsessionController.skipToQueueItem(queueItemId, () => {
  console.info('Succeeded in skipping to queue item.');
});

getOutputDevice10+

getOutputDevice(): Promise<OutputDeviceInfo>

Obtains the output device information. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<OutputDeviceInfo> Promise used to return the information obtained.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
600101 Session service exception.
600103 The session controller does not exist.

Example


avsessionController.getOutputDevice().then((deviceInfo: avSession.OutputDeviceInfo) => {
  console.info('Succeeded in getting output device.');
});

getOutputDevice10+

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> Yes Callback used to return the information obtained.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
600101 Session service exception.
600103 The session controller does not exist.

Example


avsessionController.getOutputDevice((deviceInfo: avSession.OutputDeviceInfo) => {
  console.info('Succeeded in getting output device.');
});

sendAVKeyEvent10+

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.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
event KeyEvent Yes Key event.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed.
600101 Session service exception.
600102 The session does not exist.
600103 The session controller does not exist.
600105 Invalid session command.
600106 The session is not activated.

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

import { Key, KeyEvent } from '@kit.InputKit';

let keyItem: Key = {code:0x49, pressedTime:2, deviceId:0};
let event:KeyEvent = {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};


avsessionController.sendAVKeyEvent(event).then(() => {
  console.info('Succeeded in sending AV key event.');
});

sendAVKeyEvent10+

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 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 Universal Error Codes and AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed.
600101 Session service exception.
600102 The session does not exist.
600103 The session controller does not exist.
600105 Invalid session command.
600106 The session is not activated.

Example

import { Key, KeyEvent } from '@kit.InputKit';

let keyItem: Key = {code:0x49, pressedTime:2, deviceId:0};
let event:KeyEvent = {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};
avsessionController.sendAVKeyEvent(event, () => {
  console.info('Succeeded in sending AV key event.');
});

getLaunchAbility10+

getLaunchAbility(): Promise<WantAgent>

Obtains the WantAgent object saved by the application in the session. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<WantAgent> Promise used to return the object saved by calling setLaunchAbility. The object includes the application property, such as the bundle name, ability name, and device ID.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


avsessionController.getLaunchAbility().then((agent: object) => {
  console.info(`Succeeded in getting launch ability: ${agent}`);
});

getLaunchAbility10+

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> Yes Callback used to return the object saved by calling setLaunchAbility. The object includes the application property, such as the bundle name, ability name, and device ID.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


avsessionController.getLaunchAbility((agent: object) => {
  console.info(`Succeeded in getting launch ability: ${agent}`);
});

getRealPlaybackPositionSync10+

getRealPlaybackPositionSync(): number

Obtains the playback position.

Atomic service API: This API can be used in atomic services since API version 12.

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.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example

let time: number = avsessionController.getRealPlaybackPositionSync();

isActive10+

isActive(): Promise<boolean>

Checks whether the session is activated. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<boolean> Promise used to return the result indicating whether the session is activated. true if activated, false otherwise.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


avsessionController.isActive().then((isActive: boolean) => {
  console.info(`Succeeded in checking active state: ${isActive}`);
});

isActive10+

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 whether the session is activated. true if activated, false otherwise.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


avsessionController.isActive((isActive: boolean) => {
  console.info(`Succeeded in checking active state: ${isActive}`);
});

destroy10+

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.

Atomic service API: This API can be used in atomic services since API version 12.

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.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example


avsessionController.destroy().then(() => {
  console.info('Succeeded in destroying.');
});

destroy10+

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.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example


avsessionController.destroy(() => {
  console.info('Succeeded in destroying.');
});

getValidCommands10+

getValidCommands(): Promise<Array<AVControlCommandType>>

Obtains valid commands supported by the session. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<Array<AVControlCommandType>> Promise used to return a set of valid commands.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


avsessionController.getValidCommands().then((validCommands: avSession.AVControlCommandType[]) => {
  console.info(`Succeeded in getting valid commands, size: ${validCommands.length}`);
});

getValidCommands10+

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>> Yes Callback used to return a set of valid commands.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example


avsessionController.getValidCommands((validCommands: avSession.AVControlCommandType[]) => {
  console.info(`Succeeded in getting valid commands, size: ${validCommands.length}`);
});

sendControlCommand10+

sendControlCommand(command: AVControlCommand): Promise<void>

Sends a control command to the session through the controller. This API uses a promise to return the result.

NOTE

Before using sendControlCommand, the controller must ensure that the corresponding listeners are registered for the media session. For details about how to register the listeners, see on('play'), on('pause'), and the like.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
command 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 Universal Error Codes and AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed.
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600105 Invalid session command.
6600106 The session is not activated.
6600107 Too many commands or events.

Example


let avCommand: avSession.AVControlCommand = {command:'play'};
avsessionController.sendControlCommand(avCommand).then(() => {
  console.info('Succeeded in sending control command.');
});

sendControlCommand10+

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.

NOTE

Before using sendControlCommand, the controller must ensure that the corresponding listeners are registered for the media session. For details about how to register the listeners, see on('play'), on('pause'), and the like.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
command 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 Universal Error Codes and AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed.
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600105 Invalid session command.
6600106 The session is not activated.
6600107 Too many commands or events.

Example


let avCommand: avSession.AVControlCommand = {command:'play'};
avsessionController.sendControlCommand(avCommand, () => {
  console.info('Succeeded in sending control command.');
});

sendCommonCommand10+

sendCommonCommand(command: string, args: {[key: string]: Object}): Promise<void>

Sends a custom control command to the session through the controller. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
command string Yes Name of the custom control command.
args {[key: string]: Object} Yes Parameters in key-value pair format carried in the custom control command.

NOTE

The args parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see @ohos.app.ability.Want (Want).

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed.
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600105 Invalid session command.
6600106 The session is not activated.
6600107 Too many commands or events.

Example

import { avSession } from '@kit.AVSessionKit';

let tag: string = "createNewSession";
let sessionId: string = "";
let controller:avSession.AVSessionController | undefined = undefined;
avSession.createAVSession(context, tag, "audio").then(async (data:avSession.AVSession)=> {
  currentAVSession = data;
  sessionId = currentAVSession.sessionId;
  controller = await currentAVSession.getController();
  console.info(`Succeeded in creating AV session, sessionId: ${sessionId}`);
});
let commandName = "my_command";
if (controller !== undefined) {
  (controller as avSession.AVSessionController).sendCommonCommand(commandName, {command : "This is my command"}).then(() => {
    console.info('Succeeded in sending common command.');
  })
}

sendCommonCommand10+

sendCommonCommand(command: string, args: {[key: string]: Object}, callback: AsyncCallback<void>): void

Sends a custom 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 string Yes Name of the custom control command.
args {[key: string]: Object} Yes Parameters in key-value pair format carried in the custom control command.
callback AsyncCallback<void> Yes Callback used to return the result. If the command is sent, err is undefined; otherwise, err is an error object.

NOTE

The args parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see @ohos.app.ability.Want (Want).

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed.
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600105 Invalid session command.
6600106 The session is not activated.
6600107 Too many commands or events.

Example

import { avSession } from '@kit.AVSessionKit';
          
let tag: string = "createNewSession";
let sessionId: string = "";
let controller:avSession.AVSessionController | undefined = undefined;
avSession.createAVSession(context, tag, "audio").then(async (data:avSession.AVSession)=> {
  currentAVSession = data;
  sessionId = currentAVSession.sessionId;
  controller = await currentAVSession.getController();
  console.info(`Succeeded in creating AV session, sessionId: ${sessionId}`);
});
let commandName = "my_command";
if (controller !== undefined) {
  (controller as avSession.AVSessionController).sendCommonCommand(commandName, {command : "This is my command"}, () => {
    console.info('Succeeded in sending common command.');
  })
}

sendCustomData20+

sendCustomData(data: Record<string, Object>): Promise<void>

Sends custom data to the remote device. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.Multimedia.AVSession.AVCast

Parameters

Name Type Mandatory Description
data Record<string, Object> Yes Custom data filled by the application. Only objects with the key 'customData' and of the type string are parsed on the server.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.You are advised to:1.Scheduled retry.2.Destroy the current session or session controller and re-create it.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  private tag: string = "createNewSession";
  private sessionId: string = "";
  private controller: avSession.AVSessionController | undefined = undefined;
  private currentAVSession?: avSession.AVSession;
  context = this.getUIContext();

  aboutToAppear(): void {
    avSession.createAVSession(this.getUIContext().getHostContext(), this.tag, "audio")
      .then(async (data: avSession.AVSession) => {
        this.currentAVSession = data;
        this.sessionId = this.currentAVSession.sessionId;
        this.controller = await this.currentAVSession.getController();
        console.info(`Succeeded in creating AV session, sessionId: ${this.sessionId}`);
      });

    if (this.controller !== undefined) {
      (this.controller as avSession.AVSessionController).sendCustomData({ customData: "This is my data" })
    }
  }

  build() {
    Column() {
      Text('AVSession Demo')
        .fontSize(20)
        .margin(10)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

getExtras10+

getExtras(): Promise<{[key: string]: Object}>

Obtains the custom media packet set by the provider. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<{[key: string]: Object}> Promise used to return the custom media packet. The content of the packet is the same as that set in setExtras.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600105 Invalid session command.
6600107 Too many commands or events.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  private tag: string = "createNewSession";
  private sessionId: string = "";
  private controller: avSession.AVSessionController | undefined = undefined;
  private currentAVSession?: avSession.AVSession;
  context = this.getUIContext();

  aboutToAppear(): void {

    avSession.createAVSession(this.getUIContext().getHostContext(), this.tag, "audio")
      .then(async (data: avSession.AVSession) => {
        this.currentAVSession = data;
        this.sessionId = this.currentAVSession.sessionId;
        this.controller = await this.currentAVSession.getController();
        console.info(`Succeeded in creating AV session, sessionId: ${this.sessionId}`);
      });
    if (this.controller !== undefined) {
      (this.controller as avSession.AVSessionController).getExtras().then((extras) => {
        console.info(`Succeeded in getting extras: ${extras}`);
      });
    }
  }

  build() {
    Column() {
      Text('AVSession Demo')
        .fontSize(20)
        .margin(10)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

getExtras10+

getExtras(callback: AsyncCallback<{[key: string]: Object}>): void

Obtains the custom media packet set by the provider. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
callback AsyncCallback<{[key: string]: Object}> Yes Callback used to return the custom media packet. The content of the packet is the same as that set in setExtras.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600105 Invalid session command.
6600107 Too many commands or events.

Example

import { avSession } from '@kit.AVSessionKit';

let tag: string = "createNewSession";
let sessionId: string = "";
let controller:avSession.AVSessionController | undefined = undefined;
avSession.createAVSession(context, tag, "audio").then(async (data:avSession.AVSession)=> {
  currentAVSession = data;
  sessionId = currentAVSession.sessionId;
  controller = await currentAVSession.getController();
  console.info(`Succeeded in creating AV session, sessionId: ${sessionId}`);
});
if (controller !== undefined) {
  (controller as avSession.AVSessionController).getExtras((extras) => {
    console.info(`Succeeded in getting extras: ${extras}`);
  });
}

getExtrasWithEvent18+

getExtrasWithEvent(extraEvent: string): Promise<ExtraInfo>

Obtains the custom media packet set by the remote distributed media provider based on the remote distributed event type. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
extraEvent string Yes Remote distributed event type. The event types that can be obtained from setExtras.
For wearable devices, the following preset event types are additionally provided:
'AUDIO_GET_VOLUME': obtains the volume of the remote device.
'AUDIO_GET_AVAILABLE_DEVICES': obtains all remote devices that can be connected.
'AUDIO_GET_PREFERRED_OUTPUT_DEVICE_FOR_RENDERER_INFO': obtains the actual remote audio device.

Return value

Type Description
Promise<ExtraInfo> Promise used to return the custom media packet set by the remote distributed media provider.
The ExtraInfo parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see @ohos.app.ability.Want (Want).

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600105 Invalid session command.

Example


let controller: avSession.AVSessionController | ESObject;
const COMMON_COMMAND_STRING_1 = 'AUDIO_GET_VOLUME';
const COMMON_COMMAND_STRING_2 = 'AUDIO_GET_AVAILABLE_DEVICES';
const COMMON_COMMAND_STRING_3 = 'AUDIO_GET_PREFERRED_OUTPUT_DEVICE_FOR_RENDERER_INFO';
if (controller !== undefined) {
  controller.getExtrasWithEvent(COMMON_COMMAND_STRING_1).then(() => {
    console.info(`${[COMMON_COMMAND_STRING_1]}`);
  })

  controller.getExtrasWithEvent(COMMON_COMMAND_STRING_2).then(() => {
    console.info(`${[COMMON_COMMAND_STRING_2]}`);
  })

  controller.getExtrasWithEvent(COMMON_COMMAND_STRING_3).then(() => {
    console.info(`${[COMMON_COMMAND_STRING_3]}`);
  })
}

isDesktopLyricEnabled23+

isDesktopLyricEnabled(): Promise<boolean>

Checks whether the desktop lyrics feature is enabled. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<boolean> Promise used to return the result. The value true indicates that the desktop lyrics feature is enabled, and false indicates the opposite.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600111 The desktop lyrics feature is not supported.
import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello world';

  build() {
    Column() {
      Text(this.message)
        .onClick(async () => {
          let tag: string = "createNewSession";
          let context: Context = this.getUIContext().getHostContext() as Context;
          let currentAVSession: avSession.AVSession = await avSession.createAVSession(context, tag, "audio");
          console.info(`Succeeded in creating AV session, sessionId: ${currentAVSession.sessionId}`);
          let controller: avSession.AVSessionController = await currentAVSession.getController();
          let enabled: boolean = await controller.isDesktopLyricEnabled()
          console.info(`desktop lyric enabled:${enabled}`)
        })
    }
    .width('100%')
    .height('100%')
  }
}

onDesktopLyricEnabled23+

onDesktopLyricEnabled(callback: Callback<boolean>): void

Subscribes to the change events of the desktop lyrics feature enabling state. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
callback Callback<boolean> Yes Callback used to return the result. The value true indicates that the desktop lyrics feature is enabled, and false indicates the opposite.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello world';

  build() {
    Column() {
      Text(this.message)
        .onClick(async () => {
          let tag: string = "createNewSession";
          let context: Context = this.getUIContext().getHostContext() as Context;
          let currentAVSession: avSession.AVSession = await avSession.createAVSession(context, tag, "audio");
          console.info(`Succeeded in creating AV session, sessionId: ${currentAVSession.sessionId}`);
          let controller: avSession.AVSessionController = await currentAVSession.getController();
          controller.onDesktopLyricEnabled((enabled: boolean) => {
            console.info(`desktop lyric enabled state : ${enabled}`);
          })
          console.info('Succeeded in setting onDesktopLyricEnabled.');
        })
    }
    .width('100%')
    .height('100%')
  }
}

offDesktopLyricEnabled23+

offDesktopLyricEnabled(callback?: Callback<boolean>): void

Unsubscribes from the change events of the desktop lyrics enabling state. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
callback Callback<boolean> No Callback used for unsubscription. If the unsubscription is successful, err is undefined; otherwise, err is an error object.
This parameter is optional. If it is not specified, the change events for the desktop lyrics enabling state of all sessions are unsubscribed.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello world';

  build() {
    Column() {
      Text(this.message)
        .onClick(async () => {
          let tag: string = "createNewSession";
          let context: Context = this.getUIContext().getHostContext() as Context;
          let currentAVSession: avSession.AVSession = await avSession.createAVSession(context, tag, "audio");
          console.info(`Succeeded in creating AV session, sessionId: ${currentAVSession.sessionId}`);
          let controller: avSession.AVSessionController = await currentAVSession.getController();
          controller.offDesktopLyricEnabled();
          console.info('Succeeded in setting offDesktopLyricEnabled.');
        })
    }
    .width('100%')
    .height('100%')
  }
}

setDesktopLyricVisible23+

setDesktopLyricVisible(visible: boolean): Promise<void>

Sets whether to display desktop lyrics in the current session. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
visible boolean Yes Whether to display desktop lyrics. true to display, false otherwise.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600110 The desktop lyrics feature of this application is not enabled.
6600111 The desktop lyrics feature is not supported.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello world';

  build() {
    Column() {
      Text(this.message)
        .onClick(async () => {
          let tag: string = "createNewSession";
          let context: Context = this.getUIContext().getHostContext() as Context;
          let currentAVSession: avSession.AVSession = await avSession.createAVSession(context, tag, "audio");
          console.info(`Succeeded in creating AV session, sessionId: ${currentAVSession.sessionId}`);
          let controller: avSession.AVSessionController = await currentAVSession.getController();
          await controller.setDesktopLyricVisible(true);
          console.info('Succeeded in setting desktop lyric visible.');
        })
    }
    .width('100%')
    .height('100%')
  }
}

isDesktopLyricVisible23+

isDesktopLyricVisible(): Promise<boolean>

Checks whether desktop lyrics are displayed in the current session. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<boolean> Promise used to return the result. If true is returned, the desktop lyrics are displayed. If false is returned, the desktop lyrics are not displayed.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600110 The desktop lyrics feature of this application is not enabled.
6600111 The desktop lyrics feature is not supported.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello world';

  build() {
    Column() {
      Text(this.message)
        .onClick(async () => {
          let tag: string = "createNewSession";
          let context: Context = this.getUIContext().getHostContext() as Context;
          let currentAVSession: avSession.AVSession = await avSession.createAVSession(context, tag, "audio");
          console.info(`Succeeded in creating AV session, sessionId: ${currentAVSession.sessionId}`);
          let controller: avSession.AVSessionController = await currentAVSession.getController();
          let visible: boolean = await controller.isDesktopLyricVisible();
          console.info(`isDesktopLyricVisible: ${visible}`);
        })
    }
    .width('100%')
    .height('100%')
  }
}

onDesktopLyricVisibilityChanged23+

onDesktopLyricVisibilityChanged(callback: Callback<boolean>): void

Subscribes to the change events of the desktop lyrics visibility. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
callback Callback<boolean> Yes Callback used to return the result. The value true indicates that the desktop lyrics are displayed, and false indicates the opposite.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello world';

  build() {
    Column() {
      Text(this.message)
        .onClick(async () => {
          let tag: string = "createNewSession";
          let context: Context = this.getUIContext().getHostContext() as Context;
          let currentAVSession: avSession.AVSession = await avSession.createAVSession(context, tag, "audio");
          console.info(`Succeeded in creating AV session, sessionId: ${currentAVSession.sessionId}`);
          let controller: avSession.AVSessionController = await currentAVSession.getController();
          controller.onDesktopLyricVisibilityChanged((visible: boolean) => {
            console.info(`desktop lyric visible state: ${visible}`);
          });
        })
    }
    .width('100%')
    .height('100%')
  }
}

offDesktopLyricVisibilityChanged23+

offDesktopLyricVisibilityChanged(callback?: Callback<boolean>): void

Unsubscribes from the change events of the desktop lyrics visibility. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
callback Callback<boolean> No Callback used for unsubscription. If the unsubscription is successful, err is undefined; otherwise, err is an error object.
This parameter is optional. If it is not specified, the change events of all sessions' desktop lyrics visibility are unsubscribed.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello world';

  build() {
    Column() {
      Text(this.message)
        .onClick(async () => {
          let tag: string = "createNewSession";
          let context: Context = this.getUIContext().getHostContext() as Context;
          let currentAVSession: avSession.AVSession = await avSession.createAVSession(context, tag, "audio");
          console.info(`Succeeded in creating AV session, sessionId: ${currentAVSession.sessionId}`);
          let controller: avSession.AVSessionController = await currentAVSession.getController();
          controller.offDesktopLyricVisibilityChanged();
        })
    }
    .width('100%')
    .height('100%')
  }
}

setDesktopLyricState23+

setDesktopLyricState(state: DesktopLyricState): Promise<void>

Sets the desktop lyric state of the current session. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
state DesktopLyricState Yes Desktop lyrics state.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600110 The desktop lyrics feature of this application is not enabled.
6600111 The desktop lyrics feature is not supported.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello world';

  build() {
    Column() {
      Text(this.message)
        .onClick(async () => {
          let tag: string = "createNewSession";
          let context: Context = this.getUIContext().getHostContext() as Context;
          let currentAVSession: avSession.AVSession = await avSession.createAVSession(context, tag, "audio");
          console.info(`Succeeded in creating AV session, sessionId: ${currentAVSession.sessionId}`);
          let controller: avSession.AVSessionController = await currentAVSession.getController();
          let state: avSession.DesktopLyricState = {
            isLocked: true,
          };
          await controller.setDesktopLyricState(state);
          console.info('Succeeded in setting desktop lyric state.');
        })
    }
    .width('100%')
    .height('100%')
  }
}

getDesktopLyricState23+

getDesktopLyricState(): Promise<DesktopLyricState>

Obtains the desktop lyric state of the current session. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<DesktopLyricState> Promise used to return the desktop lyrics state.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.
6600110 The desktop lyrics feature of this application is not enabled.
6600111 The desktop lyrics feature is not supported.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello world';

  build() {
    Column() {
      Text(this.message)
        .onClick(async () => {
          let tag: string = "createNewSession";
          let context: Context = this.getUIContext().getHostContext() as Context;
          let currentAVSession: avSession.AVSession = await avSession.createAVSession(context, tag, "audio");
          console.info(`Succeeded in creating AV session, sessionId: ${currentAVSession.sessionId}`);
          let controller: avSession.AVSessionController = await currentAVSession.getController();
          let state: avSession.DesktopLyricState = await controller.getDesktopLyricState();
          console.info(`getDesktopLyricState: ${state.isLocked}`);
        })
    }
    .width('100%')
    .height('100%')
  }
}

onDesktopLyricStateChanged23+

onDesktopLyricStateChanged(callback: Callback<DesktopLyricState>): void

Subscribes to the change events of the desktop lyrics state. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
callback Callback<DesktopLyricState> Yes Callback used to return the desktop lyrics state.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello world';

  build() {
    Column() {
      Text(this.message)
        .onClick(async () => {
          let tag: string = "createNewSession";
          let context: Context = this.getUIContext().getHostContext() as Context;
          let currentAVSession: avSession.AVSession = await avSession.createAVSession(context, tag, "audio");
          console.info(`Succeeded in creating AV session, sessionId: ${currentAVSession.sessionId}`);
          let controller: avSession.AVSessionController = await currentAVSession.getController();
          controller.onDesktopLyricStateChanged((state: avSession.DesktopLyricState) => {
            console.info(`desktop lyric isLocked : ${state.isLocked}`);
          })
        })
    }
    .width('100%')
    .height('100%')
  }
}

offDesktopLyricStateChanged23+

offDesktopLyricStateChanged(callback?: Callback<DesktopLyricState>): void

Unsubscribes from the change events of the desktop lyrics state. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
callback Callback<DesktopLyricState> No Callback used for unsubscription. If the unsubscription is successful, err is undefined; otherwise, err is an error object.
This parameter is optional. If it is not specified, the change events of all sessions' desktop lyrics state are unsubscribed.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example

import { avSession } from '@kit.AVSessionKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello world';

  build() {
    Column() {
      Text(this.message)
        .onClick(async () => {
          let tag: string = "createNewSession";
          let context: Context = this.getUIContext().getHostContext() as Context;
          let currentAVSession: avSession.AVSession = await avSession.createAVSession(context, tag, "audio");
          console.info(`Succeeded in creating AV session, sessionId: ${currentAVSession.sessionId}`);
          let controller: avSession.AVSessionController = await currentAVSession.getController();
          controller.offDesktopLyricStateChanged();
        })
    }
    .width('100%')
    .height('100%')
  }
}

on('metadataChange')10+

on(type: 'metadataChange', filter: Array<keyof AVMetadata> | 'all', callback: (data: AVMetadata) => void)

Subscribes to metadata change events.

Multiple callbacks can be registered for this event. To ensure only the latest callback executes, unregister previous listeners first. Otherwise, all registered callbacks will fire on state changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'metadataChange' is triggered when the session metadata requires an update.
"Requires an update" means the corresponding property value has been reset, regardless of whether the new value matches the old one.
filter Array<keyof AVMetadata>|'all' Yes The value 'all' indicates that any call state field change will trigger the event, and Array<keyof AVMetadata> indicates that only changes to the listed call state field will trigger the event.
callback (data: AVMetadata) => void Yes Callback used for subscription. The data parameter in the callback indicates the metadata that requires an update, but not the complete current metadata set.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.on('metadataChange', 'all', (metadata: avSession.AVMetadata) => {
  console.info(`on metadataChange assetId : ${metadata.assetId}`);
});

avsessionController.on('metadataChange', ['assetId', 'title', 'description'], (metadata: avSession.AVMetadata) => {
  console.info(`on metadataChange assetId : ${metadata.assetId}`);
});

off('metadataChange')10+

off(type: 'metadataChange', callback?: (data: AVMetadata) => void)

Unsubscribes from metadata change events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'metadataChange' in this case.
callback (data: AVMetadata) => void No Callback used for subscription. The data parameter in the callback indicates the metadata that requires an update, but not the complete current metadata set.
The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('metadataChange');

on('playbackStateChange')10+

on(type: 'playbackStateChange', filter: Array<keyof AVPlaybackState> | 'all', callback: (state: AVPlaybackState) => void)

Subscribes to playback state change events.

Multiple callbacks can be registered for this event. To ensure only the latest callback executes, unregister previous listeners first. Otherwise, all registered callbacks will fire on state changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'playbackStateChange' is triggered when the playback state requires an update.
"Requires an update" means the corresponding property value has been reset, regardless of whether the new value matches the old one.
filter Array<keyof AVPlaybackState>|'all' Yes The value 'all' indicates monitoring for updates to all playback state fields,
while Array<keyof AVPlaybackstate> indicates monitoring for updates to fields in the array.
callback (state: AVPlaybackState) => void Yes Callback function, where the state parameter indicates the playback state that requires an update, but not the complete current playback state set.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  console.info(`on playbackStateChange state : ${playbackState.state}`);
});

avsessionController.on('playbackStateChange', ['state', 'speed', 'loopMode'], (playbackState: avSession.AVPlaybackState) => {
  console.info(`on playbackStateChange state : ${playbackState.state}`);
});

off('playbackStateChange')10+

off(type: 'playbackStateChange', callback?: (state: AVPlaybackState) => void)

Unsubscribes from playback state change events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'playbackStateChange' in this case.
callback (state: AVPlaybackState) => void No Callback function, where the state parameter indicates the playback state that requires an update, but not the complete current playback state set.
The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('playbackStateChange');

on('callMetadataChange')11+

on(type: 'callMetadataChange', filter: Array<keyof CallMetadata> | 'all', callback: Callback<CallMetadata>): void

Subscribes to call metadata change events.

Multiple callbacks can be registered for this event. To ensure only the latest callback executes, unregister previous listeners first. Otherwise, all registered callbacks will fire on state changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'callMetadataChange' is triggered when the call metadata changes.
filter Array<keyof CallMetadata>|'all' Yes 'all' indicates that any call metadata field change will trigger the event, and Array<keyof CallMetadata> indicates that only changes to the listed metadata field will trigger the event. | 'all'.
callback Callback<CallMetadata> Yes Callback used for subscription. The callmetadata parameter in the callback indicates the changed call metadata.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.on('callMetadataChange', 'all', (callmetadata: avSession.CallMetadata) => {
  console.info(`on callMetadataChange state : ${callmetadata.name}`);
});

avsessionController.on('callMetadataChange', ['name'], (callmetadata: avSession.CallMetadata) => {
  console.info(`on callMetadataChange state : ${callmetadata.name}`);
});

off('callMetadataChange')11+

off(type: 'callMetadataChange', callback?: Callback<CallMetadata>): void

Unsubscribes from call metadata change events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'callMetadataChange' in this case.
callback Callback<CallMetadata> No Callback used for unsubscription. The calldata parameter in the callback indicates the changed call metadata.
The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('callMetadataChange');

on('callStateChange')11+

on(type: 'callStateChange', filter: Array<keyof AVCallState> | 'all', callback: Callback<AVCallState>): void

Subscribes to call state change events.

Multiple callbacks can be registered for this event. To ensure only the latest callback executes, unregister previous listeners first. Otherwise, all registered callbacks will fire on state changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'callStateChange' is triggered when the call state changes.
filter Array<keyof AVCallState>|'all' Yes 'all' indicates that any call state field change will trigger the event, and Array<keyof AVCallState> indicates that only changes to the listed call state field will trigger the event. | 'all'.
callback Callback<AVCallState> Yes Callback function, where the callstate parameter indicates the new call state.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified.2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.on('callStateChange', 'all', (callstate: avSession.AVCallState) => {
  console.info(`on callStateChange state : ${callstate.state}`);
});

avsessionController.on('callStateChange', ['state'], (callstate: avSession.AVCallState) => {
  console.info(`on callStateChange state : ${callstate.state}`);
});

off('callStateChange')11+

off(type: 'callStateChange', callback?: Callback<AVCallState>): void

Unsubscribes from call state change events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'callStateChange' in this case.
callback Callback<AVCallState> No Callback function, where the callstate parameter indicates the new call metadata.
The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('callMetadataChange');

on('sessionDestroy')10+

on(type: 'sessionDestroy', callback: () => void)

Subscribes to session destruction events.

Multiple callbacks can be registered for this event. To ensure only the latest callback executes, unregister previous listeners first. Otherwise, all registered callbacks will fire on state changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. Event 'sessionDestroy' is triggered when a 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 Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.on('sessionDestroy', () => {
  console.info('Succeeded in session destroy.');
});

off('sessionDestroy')10+

off(type: 'sessionDestroy', callback?: () => void)

Unsubscribes from session destruction events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'sessionDestroy' in this case.
callback () => void No Callback used for unsubscription. If the unsubscription is successful, err is undefined; otherwise, err is an error object.
The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified.2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('sessionDestroy');

on('activeStateChange')10+

on(type: 'activeStateChange', callback: (isActive: boolean) => void)

Subscribes to session activation state change events.

Multiple callbacks can be registered for this event. To ensure only the latest callback executes, unregister previous listeners first. Otherwise, all registered callbacks will fire on state changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'activeStateChange' is triggered 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. true if activated, false otherwise.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.on('activeStateChange', (isActive: boolean) => {
  console.info(`Succeeded in active state change: ${isActive}`);
});

off('activeStateChange')10+

off(type: 'activeStateChange', callback?: (isActive: boolean) => void)

Unsubscribes from session activation state change events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'activeStateChange' in this case.
callback (isActive: boolean) => void No Callback used for unsubscription. The isActive parameter in the callback specifies whether the session is activated. true if activated, false otherwise.
The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('activeStateChange');

on('validCommandChange')10+

on(type: 'validCommandChange', callback: (commands: Array<AVControlCommandType>) => void)

Subscribes to valid command change events.

Multiple callbacks can be registered for this event. To ensure only the latest callback executes, unregister previous listeners first. Otherwise, all registered callbacks will fire on state changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'validCommandChange' is triggered when the valid commands supported by the session changes.
callback (commands: Array<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 Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.on('validCommandChange', (validCommands: avSession.AVControlCommandType[]) => {
  console.info(`Succeeded in valid command change, size: ${validCommands.length}`);
  console.info(`Succeeded in valid command change, validCommands: ${validCommands.values()}`);
});

off('validCommandChange')10+

off(type: 'validCommandChange', callback?: (commands: Array<AVControlCommandType>) => void)

Unsubscribes from valid command change events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'validCommandChange' in this case.
callback (commands: Array<AVControlCommandType>) => void No Callback used for unsubscription. The commands parameter in the callback is a set of valid commands.
The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('validCommandChange');

on('outputDeviceChange')10+

on(type: 'outputDeviceChange', callback: (state: ConnectionState, device: OutputDeviceInfo) => void): void

Subscribes to output device change events.

Multiple callbacks can be registered for this event. To ensure only the latest callback executes, unregister previous listeners first. Otherwise, all registered callbacks will fire on state changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'outputDeviceChange' is triggered when the output device changes.
callback (state: ConnectionState, device: 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.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.on('outputDeviceChange', (state: avSession.ConnectionState, device: avSession.OutputDeviceInfo) => {
  console.info(`on outputDeviceChange state: ${state}, device : ${device}`);
});

off('outputDeviceChange')10+

off(type: 'outputDeviceChange', callback?: (state: ConnectionState, device: OutputDeviceInfo) => void): void

Unsubscribes from output device change events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'outputDeviceChange' in this case.
callback (state: ConnectionState, device: OutputDeviceInfo) => void No Callback function, where the device parameter specifies the output device information.
The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('outputDeviceChange');

on('sessionEvent')10+

on(type: 'sessionEvent', callback: (sessionEvent: string, args: {[key: string]: Object}) => void): void

Subscribes to session event change events. This API is called by the controller.

Multiple callbacks can be registered for this event. To ensure only the latest callback executes, unregister previous listeners first. Otherwise, all registered callbacks will fire on state changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'sessionEvent' is triggered when the session event changes.
callback (sessionEvent: string, args: {[key: string]: Object}) => void Yes Callback used for subscription. sessionEvent in the callback indicates the name of the session event that changes, and args indicates the parameters carried in the event.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

import { avSession } from '@kit.AVSessionKit';
       
let tag: string = "createNewSession";
let sessionId: string = "";
let controller:avSession.AVSessionController | undefined = undefined;
avSession.createAVSession(context, tag, "audio").then(async (data:avSession.AVSession)=> {
  currentAVSession = data;
  sessionId = currentAVSession.sessionId;
  controller = await currentAVSession.getController();
  console.info(`Succeeded in creating AV session, sessionId: ${sessionId}`);
});
if (controller !== undefined) {
  (controller as avSession.AVSessionController).on('sessionEvent', (sessionEvent, args) => {
    console.info(`OnSessionEvent, sessionEvent is ${sessionEvent}, args: ${JSON.stringify(args)}`);
  });
}

off('sessionEvent')10+

off(type: 'sessionEvent', callback?: (sessionEvent: string, args: {[key: string]: Object}) => void): void

Unsubscribes from session events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'sessionEvent' in this case.
callback (sessionEvent: string, args: {[key: string]: Object}) => void No Callback used for unsubscription. sessionEvent in the callback indicates the name of the session event that changes, and args indicates the parameters carried in the event.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('sessionEvent');

on('queueItemsChange')10+

on(type: 'queueItemsChange', callback: (items: Array<AVQueueItem>) => void): void

Subscribes to playlist item change events. This API is called by the controller.

Multiple callbacks can be registered for this event. To ensure only the latest callback executes, unregister previous listeners first. Otherwise, all registered callbacks will fire on state changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'queueItemsChange' is triggered when one or more items in the playlist changes.
callback (items: Array<AVQueueItem>) => void Yes Callback used for subscription. The items parameter in the callback indicates the changed items in the playlist.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.on('queueItemsChange', (items: avSession.AVQueueItem[]) => {
  console.info(`OnQueueItemsChange, items length is ${items.length}`);
});

off('queueItemsChange')10+

off(type: 'queueItemsChange', callback?: (items: Array<AVQueueItem>) => void): void

Unsubscribes from playback item change events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'queueItemsChange' in this case.
callback (items: Array<AVQueueItem>) => void No Callback used for unsubscription. The items parameter in the callback indicates the changed items in the playlist.
The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('queueItemsChange');

on('queueTitleChange')10+

on(type: 'queueTitleChange', callback: (title: string) => void): void

Subscribes to playlist name change events. This API is called by the controller.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'queueTitleChange' is triggered when the playlist name changes.
callback (title: string) => void Yes Callback used for subscription. The title parameter in the callback indicates the changed playlist name.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.on('queueTitleChange', (title: string) => {
  console.info(`queueTitleChange, title is ${title}`);
});

off('queueTitleChange')10+

off(type: 'queueTitleChange', callback?: (title: string) => void): void

Unsubscribes from playlist name change events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'queueTitleChange' in this case.
callback (title: string) => void No Callback used for unsubscription. The items parameter in the callback indicates the changed playlist name.
The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Management Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('queueTitleChange');

on('extrasChange')10+

on(type: 'extrasChange', callback: (extras: {[key: string]: Object}) => void): void

Subscribes to custom media packet change events. This API is called by the controller.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'extrasChange' is triggered when the provider sets a custom media packet.
callback (extras: {[key: string]: Object}) => void Yes Callback used for subscription. The extras parameter in the callback indicates the custom media packet set by the provider. This packet is the same as that set in dispatchSessionEvent.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

import { avSession } from '@kit.AVSessionKit';

let tag: string = "createNewSession";
let sessionId: string = "";
let controller:avSession.AVSessionController | undefined = undefined;
avSession.createAVSession(context, tag, "audio").then(async (data:avSession.AVSession)=> {
  currentAVSession = data;
  sessionId = currentAVSession.sessionId;
  controller = await currentAVSession.getController();
  console.info(`Succeeded in creating AV session, sessionId: ${sessionId}`);
});
if (controller !== undefined) {
  (controller as avSession.AVSessionController).on('extrasChange', (extras) => {
    console.info(`Caught extrasChange event,the new extra is: ${JSON.stringify(extras)}`);
  });
}

off('extrasChange')10+

off(type: 'extrasChange', callback?: (extras: {[key: string]: Object}) => void): void

Unsubscribes from custom media packet change events. If a callback is specified, the corresponding listener is unregistered. If no callback is specified, all listeners for the specified event are unregistered.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'extrasChange' in this case.
callback (extras: {[key: string]: Object}) => void No Callback used for unsubscription.
The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see Universal Error Codes and AVSession Error Codes.

ID Error Message
401 parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types.
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('extrasChange');

on('customDataChange')20+

on(type: 'customDataChange', callback: Callback<Record<string, Object>>): void

Subscribes to events indicating that custom data is sent to a remote device.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.Multimedia.AVSession.AVCast

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'customDataChange' is triggered when the provider sends custom data.
callback Callback<Record<string, Object>> Yes Callback used to receive the custom data.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example

import { avSession } from '@kit.AVSessionKit';

let tag: string = "createNewSession";
let sessionId: string = "";
let controller:avSession.AVSessionController | undefined = undefined;
avSession.createAVSession(context, tag, "audio").then(async (data:avSession.AVSession)=> {
  currentAVSession = data;
  sessionId = currentAVSession.sessionId;
  controller = await currentAVSession.getController();
  console.info(`Succeeded in creating AV session, sessionId: ${sessionId}`);
});
if (controller !== undefined) {
  (controller as avSession.AVSessionController).on('customDataChange', (callback) => {
    console.info(`Caught customDataChange event,the new callback is: ${JSON.stringify(callback)}`);
  });
}

off('customDataChange')20+

off(type: 'customDataChange', callback?: Callback<Record<string, Object>>): void

Unsubscribes from events indicating that custom data is sent to a remote device.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.Multimedia.AVSession.AVCast

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'customDataChange' in this case.
callback Callback<Record<string, Object>> No Callback used for unsubscription. The callback parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example

avsessionController.off('customDataChange');

getAVPlaybackStateSync10+

getAVPlaybackStateSync(): AVPlaybackState;

Obtains the playback state of this session. This API returns the result synchronously.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
AVPlaybackState Playback state of the session.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

let playbackState: avSession.AVPlaybackState = avsessionController.getAVPlaybackStateSync();

getAVMetadataSync10+

getAVMetadataSync(): AVMetadata

Obtains the session metadata. This API returns the result synchronously.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
AVMetadata Session metadata.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

let metaData: avSession.AVMetadata = avsessionController.getAVMetadataSync();

getAVCallState11+

getAVCallState(): Promise<AVCallState>

Obtains the call state. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<AVCallState> Promise used to return the call state obtained.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

avsessionController.getAVCallState().then((callstate: avSession.AVCallState) => {
  console.info(`Succeeded in getting AV call state: ${callstate.state}`);
});

getAVCallState11+

getAVCallState(callback: AsyncCallback<AVCallState>): void

Obtains the call state. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
callback AsyncCallback<AVCallState> Yes Callback used to return the call state obtained.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

avsessionController.getAVCallState((callstate: avSession.AVCallState) => {
  console.info(`Succeeded in getting AV call state: ${callstate.state}`);
});

getCallMetadata11+

getCallMetadata(): Promise<CallMetadata>

Obtains the call metadata. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Promise<CallMetadata> Promise used to return the metadata obtained.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

avsessionController.getCallMetadata().then((calldata: avSession.CallMetadata) => {
  console.info(`Succeeded in getting call metadata, name: ${calldata.name}`);
});

getCallMetadata11+

getCallMetadata(callback: AsyncCallback<CallMetadata>): void

Obtains the call metadata. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.AVSession.Core

Parameters

Name Type Mandatory Description
callback AsyncCallback<CallMetadata> Yes Callback used to return the metadata obtained.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

avsessionController.getCallMetadata((calldata: avSession.CallMetadata) => {
  console.info(`Succeeded in getting call metadata, name: ${calldata.name}`);
});

getAVQueueTitleSync10+

getAVQueueTitleSync(): string

Obtains the name of the playlist of this session. This API returns the result synchronously.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
string Playlist name.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

let currentQueueTitle: string = avsessionController.getAVQueueTitleSync();

getAVQueueItemsSync10+

getAVQueueItemsSync(): Array<AVQueueItem>

Obtains the information related to the items in the playlist of this session. This API returns the result synchronously.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Array<AVQueueItem> Items in the queue.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

let currentQueueItems: Array<avSession.AVQueueItem> = avsessionController.getAVQueueItemsSync();

getOutputDeviceSync10+

getOutputDeviceSync(): OutputDeviceInfo

Obtains the output device information. This API returns the result synchronously.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
OutputDeviceInfo Information about the output device.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600103 The session controller does not exist.

Example

let currentOutputDevice: avSession.OutputDeviceInfo = avsessionController.getOutputDeviceSync();

isActiveSync10+

isActiveSync(): boolean

Checks whether the session is activated. This API returns the result synchronously.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
boolean Check result for whether the session is activated. true if activated, false otherwise.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

let isActive: boolean = avsessionController.isActiveSync();

getValidCommandsSync10+

getValidCommandsSync(): Array<AVControlCommandType>

Obtains valid commands supported by the session. This API returns the result synchronously.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Multimedia.AVSession.Core

Return value

Type Description
Array<AVControlCommandType> A set of valid commands.

Error codes

For details about the error codes, see AVSession Management Error Codes.

ID Error Message
6600101 Session service exception.
6600102 The session does not exist.
6600103 The session controller does not exist.

Example

let validCommands: Array<avSession.AVControlCommandType> = avsessionController.getValidCommandsSync();