• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.multimedia.avsession (AVSession Management)
2
3The **avSession** module provides APIs for media playback control so that applications can access the system's Media Controller.
4
5This module provides the following typical features related to media sessions:
6
7- [AVSession](#avsession10): used to set session metadata, playback state information, and more.
8- [AVSessionController](#avsessioncontroller10): used to obtain session IDs, send commands and events to sessions, and obtain the session metadata and playback state information.
9- [AVCastController](#avcastcontroller10): used to control playback, listen for remote playback state changes, and obtain the remote playback state in casting scenarios.
10
11> **NOTE**
12>
13> 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.
14
15## Modules to Import
16
17```ts
18import avSession from '@ohos.multimedia.avsession';
19```
20
21## avSession.createAVSession<sup>10+</sup>
22
23createAVSession(context: Context, tag: string, type: AVSessionType): Promise\<AVSession>
24
25Creates a media session. This API uses a promise to return the result. An ability can have only one session, and repeated calling of this API fails.
26
27**System capability**: SystemCapability.Multimedia.AVSession.Core
28
29**Parameters**
30
31| Name| Type                           | Mandatory| Description                          |
32| ------ | ------------------------------- | ---- | ------------------------------ |
33| context| [Context](js-apis-inner-app-context.md) | Yes| Application context, which provides application environment information.|
34| tag    | string                          | Yes  | Custom session name.            |
35| type   | [AVSessionType](#avsessiontype10) | Yes  | Session type, which can be audio or video.|
36
37**Return value**
38
39| Type                             | Description                                                        |
40| --------------------------------- | ------------------------------------------------------------ |
41| Promise<[AVSession](#avsession10)\> | Promise used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.|
42
43**Error codes**
44
45For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
46
47| ID| Error Message|
48| -------- | ---------------------------------------- |
49| 6600101  | Session service exception. |
50
51**Example**
52
53```ts
54import { BusinessError } from '@ohos.base';
55
56let currentAVSession: avSession.AVSession;
57let tag = "createNewSession";
58let context: Context = getContext(this);
59let sessionId: string;  // Used as an input parameter of subsequent functions.
60
61avSession.createAVSession(context, tag, "audio").then((data: avSession.AVSession) => {
62  currentAVSession = data;
63  sessionId = currentAVSession.sessionId;
64  console.info(`CreateAVSession : SUCCESS : sessionId = ${sessionId}`);
65}).catch((err: BusinessError) => {
66  console.info(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
67});
68```
69
70## avSession.createAVSession<sup>10+</sup>
71
72createAVSession(context: Context, tag: string, type: AVSessionType, callback: AsyncCallback\<AVSession>): void
73
74Creates a media session. This API uses an asynchronous callback to return the result. An ability can have only one session, and repeated calling of this API fails.
75
76**System capability**: SystemCapability.Multimedia.AVSession.Core
77
78**Parameters**
79
80| Name  | Type                                   | Mandatory| Description                                                        |
81| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
82| context| [Context](js-apis-inner-app-context.md) | Yes| Application context, which provides application environment information.    |
83| tag      | string                                  | Yes  | Custom session name.                                          |
84| type     | [AVSessionType](#avsessiontype10)         | Yes  | Session type, which can be audio or video.                              |
85| callback | AsyncCallback<[AVSession](#avsession10)\> | Yes  | Callback used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.|
86
87**Error codes**
88
89For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
90
91| ID| Error Message|
92| -------- | ---------------------------------------- |
93| 6600101  | Session service exception. |
94
95**Example**
96
97```ts
98import { BusinessError } from '@ohos.base';
99
100let currentAVSession: avSession.AVSession;
101let tag = "createNewSession";
102let context: Context = getContext(this);
103let sessionId: string;  // Used as an input parameter of subsequent functions.
104
105avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
106  if (err) {
107    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
108  } else {
109    currentAVSession = data;
110    sessionId = currentAVSession.sessionId;
111    console.info(`CreateAVSession : SUCCESS : sessionId = ${sessionId}`);
112  }
113});
114```
115
116## avSession.getAllSessionDescriptors
117
118getAllSessionDescriptors(): Promise\<Array\<Readonly\<AVSessionDescriptor>>>
119
120Obtains the descriptors of all sessions. This API uses a promise to return the result.
121
122**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
123
124**System capability**: SystemCapability.Multimedia.AVSession.Manager
125
126**System API**: This is a system API.
127
128**Return value**
129
130| Type                                                        | Description                                         |
131| ------------------------------------------------------------ | --------------------------------------------- |
132| Promise\<Array\<Readonly\<[AVSessionDescriptor](#avsessiondescriptor)\>\>\> | Promise used to return an array of **AVSessionDescriptor** objects, each of which is read only.|
133
134**Error codes**
135
136For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
137
138| ID| Error Message|
139| -------- | ---------------------------------------- |
140| 6600101  | Session service exception. |
141
142**Example**
143
144```ts
145import { BusinessError } from '@ohos.base';
146
147avSession.getAllSessionDescriptors().then((descriptors: avSession.AVSessionDescriptor[]) => {
148  console.info(`getAllSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`);
149  if (descriptors.length > 0 ) {
150    console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`);
151    console.info(`GetAllSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`);
152    console.info(`GetAllSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`);
153  }
154}).catch((err: BusinessError) => {
155  console.error(`GetAllSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`);
156});
157```
158
159## avSession.getAllSessionDescriptors
160
161getAllSessionDescriptors(callback: AsyncCallback\<Array\<Readonly\<AVSessionDescriptor>>>): void
162
163Obtains the descriptors of all sessions. This API uses an asynchronous callback to return the result.
164
165**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
166
167**System capability**: SystemCapability.Multimedia.AVSession.Manager
168
169**System API**: This is a system API.
170
171**Parameters**
172
173| Name  | Type                                                        | Mandatory| Description                                      |
174| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ |
175| callback | AsyncCallback<Array<Readonly<[AVSessionDescriptor](#avsessiondescriptor)\>\>\> | Yes  | Callback used to return an array of **AVSessionDescriptor** objects, each of which is read only.|
176
177**Error codes**
178
179For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
180
181| ID| Error Message|
182| -------- | ---------------------------------------- |
183| 6600101  |Session service exception. |
184
185**Example**
186
187```ts
188import { BusinessError } from '@ohos.base';
189
190avSession.getAllSessionDescriptors((err: BusinessError, descriptors: avSession.AVSessionDescriptor[]) => {
191  if (err) {
192    console.error(`GetAllSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`);
193  } else {
194    console.info(`GetAllSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`);
195    if (descriptors.length > 0 ) {
196        console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`);
197        console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`);
198        console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`);
199    }
200  }
201});
202```
203
204## avSession.getHistoricalSessionDescriptors<sup>10+</sup>
205
206getHistoricalSessionDescriptors(maxSize?: number): Promise\<Array\<Readonly\<AVSessionDescriptor>>>
207
208Obtains the descriptors of all historical sessions. This API uses a promise to return the result.
209
210**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
211
212**System capability**: SystemCapability.Multimedia.AVSession.Manager
213
214**System API**: This is a system API.
215
216**Parameters**
217
218| Name  | Type   | Mandatory| Description                                                            |
219| -------- | ------ | ---- | -----------------------------------------------------------------|
220| maxSize  | number | No  | Maximum number of descriptors to obtain. The value ranges from 0 to 10. If this parameter is left blank, the default value **3** is used.|
221
222**Return value**
223
224| Type                                                                       | Description                                  |
225| --------------------------------------------------------------------------- | -------------------------------------- |
226| Promise\<Array\<Readonly\<[AVSessionDescriptor](#avsessiondescriptor)\>\>\> | Promise used to return an array of **AVSessionDescriptor** objects, each of which is read only.|
227
228**Error codes**
229
230For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
231
232| ID| Error Message|
233| -------- | ---------------------------------------- |
234| 6600101  | Session service exception. |
235
236**Example**
237
238```ts
239import { BusinessError } from '@ohos.base';
240
241avSession.getHistoricalSessionDescriptors().then((descriptors: avSession.AVSessionDescriptor[]) => {
242  console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`);
243  if (descriptors.length > 0 ) {
244    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`);
245    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`);
246    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`);
247    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionId : ${descriptors[0].sessionId}`);
248    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].elementName.bundleName : ${descriptors[0].elementName.bundleName}`);
249  }
250}).catch((err: BusinessError) => {
251  console.error(`getHistoricalSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`);
252});
253```
254
255## avSession.getHistoricalSessionDescriptors<sup>10+</sup>
256
257getHistoricalSessionDescriptors(maxSize: number, callback: AsyncCallback\<Array\<Readonly\<AVSessionDescriptor>>>): void
258
259Obtains the descriptors of all historical sessions. This API uses an asynchronous callback to return the result.
260
261**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
262
263**System capability**: SystemCapability.Multimedia.AVSession.Manager
264
265**System API**: This is a system API.
266
267**Parameters**
268
269| Name  | Type                                                                           | Mandatory| Description                                                            |
270| -------- | ------------------------------------------------------------------------------ | ---- | -----------------------------------------------------------------|
271| maxSize  | number                                                                         | Yes  | Maximum number of descriptors to obtain. The value ranges from 0 to 10. If this parameter is left blank, the default value **3** is used.|
272| callback | AsyncCallback<Array<Readonly<[AVSessionDescriptor](#avsessiondescriptor)\>\>\> | Yes  | Callback used to return an array of **AVSessionDescriptor** objects, each of which is read only.                             |
273
274**Error codes**
275
276For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
277
278| ID| Error Message|
279| -------- | ---------------------------------------- |
280| 6600101  |Session service exception. |
281
282**Example**
283
284```ts
285import { BusinessError } from '@ohos.base';
286
287avSession.getHistoricalSessionDescriptors(1, (err: BusinessError, descriptors: avSession.AVSessionDescriptor[]) => {
288  if (err) {
289    console.error(`getHistoricalSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`);
290  } else {
291    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`);
292    if (descriptors.length > 0 ) {
293      console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`);
294      console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`);
295      console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`);
296      console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionId : ${descriptors[0].sessionId}`);
297      console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].elementName.bundleName : ${descriptors[0].elementName.bundleName}`);
298    }
299  }
300});
301```
302
303## avSession.createController
304
305createController(sessionId: string): Promise\<AVSessionController>
306
307Creates a session controller based on the session ID. Multiple session controllers can be created. This API uses a promise to return the result.
308
309**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
310
311**System capability**: SystemCapability.Multimedia.AVSession.Manager
312
313**System API**: This is a system API.
314
315**Parameters**
316
317| Name   | Type  | Mandatory| Description    |
318| --------- | ------ | ---- | -------- |
319| sessionId | string | Yes  | Session ID. If the value is set to **'default'**, the system creates a default controller to control the system default session.|
320
321**Return value**
322
323| Type                                                 | Description                                                        |
324| ----------------------------------------------------- | ------------------------------------------------------------ |
325| Promise<[AVSessionController](#avsessioncontroller10)\> | Promise used to return the session controller created, which can be used to obtain the session ID,<br>send commands and events to sessions, and obtain metadata and playback state information.|
326
327**Error codes**
328
329For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
330
331| ID| Error Message|
332| -------- | ---------------------------------------- |
333| 6600101  | Session service exception. |
334| 6600102  | The session does not exist. |
335
336**Example**
337
338```ts
339import { BusinessError } from '@ohos.base';
340
341let currentAVcontroller: avSession.AVSessionController | undefined = undefined;
342currentAvSession.createController(sessionId).then((avcontroller: avSession.AVSessionController) => {
343  currentAVcontroller = avcontroller;
344  console.info('CreateController : SUCCESS ');
345}).catch((err: BusinessError) => {
346  console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
347});
348```
349
350## avSession.createController
351
352createController(sessionId: string, callback: AsyncCallback\<AVSessionController>): void
353
354Creates a session controller based on the session ID. Multiple session controllers can be created. This API uses an asynchronous callback to return the result.
355
356**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
357
358**System capability**: SystemCapability.Multimedia.AVSession.Manager
359
360**System API**: This is a system API.
361
362**Parameters**
363
364| Name   | Type                                                       | Mandatory| Description                                                        |
365| --------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
366| sessionId | string                                                      | Yes  | Session ID. If the value is set to **'default'**, the system creates a default controller to control the default session.                                                    |
367| callback  | AsyncCallback<[AVSessionController](#avsessioncontroller10)\> | Yes  | Callback used to return the session controller created, which can be used to obtain the session ID,<br>send commands and events to sessions, and obtain metadata and playback state information.|
368
369**Error codes**
370
371For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
372
373| ID| Error Message|
374| -------- | ---------------------------------------- |
375| 6600101  | Session service exception. |
376| 6600102  | The session does not exist. |
377
378**Example**
379
380```ts
381import { BusinessError } from '@ohos.base';
382
383let currentAVcontroller: avSession.AVSessionController | undefined = undefined;
384currentAvSession.createController(sessionId, (err: BusinessError, avcontroller: avSession.AVSessionController) => {
385  if (err) {
386    console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
387  } else {
388    currentAVcontroller = avcontroller;
389    console.info('CreateController : SUCCESS ');
390  }
391});
392```
393
394## avSession.castAudio
395
396castAudio(session: SessionToken | 'all', audioDevices: Array<audio.AudioDeviceDescriptor>): Promise\<void>
397
398Casts a session to a list of devices. This API uses a promise to return the result.
399
400Before calling this API, import the **ohos.multimedia.audio** module to obtain the descriptors of these audio devices.
401
402**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
403
404**System capability**: SystemCapability.Multimedia.AVSession.Manager
405
406**System API**: This is a system API.
407
408**Parameters**
409
410| Name       | Type          | Mandatory| Description|
411| ------------ | -------------- |------|------|
412| session      | [SessionToken](#sessiontoken) &#124; 'all' | Yes  | Session token. **SessionToken** indicates a specific token, and **'all'** indicates all tokens.|
413| audioDevices | Array\<[audio.AudioDeviceDescriptor](js-apis-audio.md#audiodevicedescriptor)\> | Yes  | Audio devices. |
414
415**Return value**
416
417| Type          | Description                         |
418| -------------- | ----------------------------- |
419| Promise\<void> | Promise used to return the result. If casting is successful, no value is returned; otherwise, an error object is returned.|
420
421**Error codes**
422
423For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
424
425| ID| Error Message|
426| -------- | ---------------------------------------- |
427| 6600101  | Session service exception. |
428| 6600102  | The session does not exist. |
429| 6600104  | The remote session connection failed. |
430
431**Example**
432
433```ts
434import audio from '@ohos.multimedia.audio';
435import { BusinessError } from '@ohos.base';
436
437let audioManager = audio.getAudioManager();
438let audioRoutingManager = audioManager.getRoutingManager();
439let audioDevices: audio.AudioDeviceDescriptors | undefined = undefined;
440audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
441  audioDevices = data;
442  console.info(`Promise returned to indicate that the device list is obtained.`);
443}).catch((err: BusinessError) => {
444  console.error(`GetDevices BusinessError: code: ${err.code}, message: ${err.message}`);
445});
446
447if (audioDevices !== undefined) {
448  avSession.castAudio('all', audioDevices as audio.AudioDeviceDescriptors).then(() => {
449    console.info(`CreateController : SUCCESS`);
450  }).catch((err: BusinessError) => {
451    console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
452  });
453}
454```
455
456## avSession.castAudio
457
458castAudio(session: SessionToken | 'all', audioDevices: Array<audio.AudioDeviceDescriptor>, callback: AsyncCallback\<void>): void
459
460Casts a session to a list of devices. This API uses an asynchronous callback to return the result.
461
462Before calling this API, import the **ohos.multimedia.audio** module to obtain the descriptors of these audio devices.
463
464**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
465
466**System capability**: SystemCapability.Multimedia.AVSession.Manager
467
468**System API**: This is a system API.
469
470**Parameters**
471
472| Name      | Type                                        | Mandatory| Description                                                        |
473| ------------ |--------------------------------------------| ---- | ------------------------------------------------------------ |
474| session      | [SessionToken](#sessiontoken) &#124; 'all' | Yes  | Session token. **SessionToken** indicates a specific token, and **'all'** indicates all tokens.|
475| audioDevices | Array\<[audio.AudioDeviceDescriptor](js-apis-audio.md#audiodevicedescriptor)\>   | Yes  | Audio devices.|
476| callback     | AsyncCallback\<void>     | Yes  | Callback used to return the result. If casting is successful, **err** is **undefined**; otherwise, **err** is an error object.     |
477
478**Error codes**
479
480For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
481
482| ID| Error Message|
483| -------- | ---------------------------------------- |
484| 6600101  | Session service exception. |
485| 6600102  | The session does not exist. |
486| 6600104  | The remote session connection failed. |
487
488**Example**
489
490```ts
491import audio from '@ohos.multimedia.audio';
492import { BusinessError } from '@ohos.base';
493
494let audioManager = audio.getAudioManager();
495let audioRoutingManager = audioManager.getRoutingManager();
496let audioDevices: audio.AudioDeviceDescriptors | undefined = undefined;
497audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
498  audioDevices = data;
499  console.info(`Promise returned to indicate that the device list is obtained.`);
500}).catch((err: BusinessError) => {
501  console.error(`GetDevices BusinessError: code: ${err.code}, message: ${err.message}`);
502});
503
504if (audioDevices !== undefined) {
505  avSession.castAudio('all', audioDevices as audio.AudioDeviceDescriptors, (err: BusinessError) => {
506    if (err) {
507      console.error(`CastAudio BusinessError: code: ${err.code}, message: ${err.message}`);
508    } else {
509      console.info(`CastAudio : SUCCESS `);
510    }
511  });
512}
513```
514
515## avSession.startAVPlayback<sup>11+</sup>
516
517startAVPlayback(bundleName: string, assetId: string): Promise\<void>
518
519Starts an application to play a media asset. This API uses a promise to return the result.
520
521**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
522
523**System capability**: SystemCapability.Multimedia.AVSession.Manager
524
525**System API**: This is a system API.
526
527**Parameters**
528
529| Name       | Type          | Mandatory| Description|
530| ------------ | -------------- |------|------|
531| bundleName   | string         | Yes  | Bundle name of the application.|
532| assetId      |string           | Yes  | ID of the media asset. |
533
534**Return value**
535
536| Type          | Description                         |
537| -------------- | ----------------------------- |
538| Promise\<void> | Promise used to return the result. If the playback is successful, no value is returned; otherwise, an error object is returned.|
539
540**Error codes**
541
542For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
543
544| ID| Error Message|
545| -------- | ---------------------------------------- |
546| 6600101  | Session service exception. |
547
548**Example**
549
550```ts
551import audio from '@ohos.multimedia.audio';
552import { BusinessError } from '@ohos.base';
553
554avSession.startAVPlayback("com.example.myapplication", "121278").then(() => {
555  console.info(`startAVPlayback : SUCCESS`);
556}).catch((err: BusinessError) => {
557  console.error(`startAVPlayback BusinessError: code: ${err.code}, message: ${err.message}`);
558});
559```
560
561## SessionToken
562
563Describes the information about a session token.
564
565**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
566
567**System capability**: SystemCapability.Multimedia.AVSession.Manager
568
569**System API**: This is a system API.
570
571| Name     | Type  | Mandatory| Description        |
572| :-------- | :----- | :--- | :----------- |
573| sessionId | string | Yes  | Session ID.      |
574| pid       | number | No  | Process ID of the session.|
575| uid       | number | No  | User ID.      |
576
577## avSession.on('sessionCreate')
578
579on(type: 'sessionCreate', callback: (session: AVSessionDescriptor) => void): void
580
581Subscribes to session creation events.
582
583**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
584
585**System capability**: SystemCapability.Multimedia.AVSession.Manager
586
587**System API**: This is a system API.
588
589**Parameters**
590
591| Name   | Type                  | Mandatory| Description                                                        |
592| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
593| type     | string                 | Yes  | Event type. The event **'sessionCreate'** is triggered when a session is created.|
594| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | Yes  | Callback used to report the session descriptor.|
595
596**Error codes**
597
598For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
599
600| ID| Error Message|
601| -------- | ---------------------------------------- |
602| 6600101  | Session service exception. |
603
604**Example**
605
606```ts
607avSession.on('sessionCreate', (descriptor: avSession.AVSessionDescriptor) => {
608  console.info(`on sessionCreate : isActive : ${descriptor.isActive}`);
609  console.info(`on sessionCreate : type : ${descriptor.type}`);
610  console.info(`on sessionCreate : sessionTag : ${descriptor.sessionTag}`);
611});
612
613```
614
615## avSession.on('sessionDestroy')
616
617on(type: 'sessionDestroy', callback: (session: AVSessionDescriptor) => void): void
618
619Subscribes to session destruction events.
620
621**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
622
623**System capability**: SystemCapability.Multimedia.AVSession.Manager
624
625**System API**: This is a system API.
626
627**Parameters**
628
629| Name  | Type           | Mandatory| Description                                                        |
630| -------- | ---------------| ---- | ------------------------------------------------------------ |
631| type     | string         | Yes  | Event type. The event **'sessionDestroy'** is triggered when a session is destroyed.|
632| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | Yes  | Callback used to report the session descriptor.|
633
634**Error codes**
635
636For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
637
638| ID| Error Message|
639| -------- | ---------------------------------------- |
640| 6600101  | Session service exception. |
641
642**Example**
643
644```ts
645avSession.on('sessionDestroy', (descriptor: avSession.AVSessionDescriptor) => {
646  console.info(`on sessionDestroy : isActive : ${descriptor.isActive}`);
647  console.info(`on sessionDestroy : type : ${descriptor.type}`);
648  console.info(`on sessionDestroy : sessionTag : ${descriptor.sessionTag}`);
649});
650```
651
652## avSession.on('topSessionChange')
653
654on(type: 'topSessionChange', callback: (session: AVSessionDescriptor) => void): void
655
656Subscribes to top session change events.
657
658**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
659
660**System capability**: SystemCapability.Multimedia.AVSession.Manager
661
662**System API**: This is a system API.
663
664**Parameters**
665
666| Name  | Type                | Mandatory| Description                                                        |
667| -------- | --------------------| ---- | ------------------------------------------------------------ |
668| type     | string      | Yes  | Event type. The event **'topSessionChange'** is triggered when the top session is changed.|
669| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | Yes  | Callback used to report the session descriptor.|
670
671**Error codes**
672
673For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
674
675| ID| Error Message|
676| -------- | ---------------------------------------- |
677| 6600101  | Session service exception. |
678
679**Example**
680
681```ts
682avSession.on('topSessionChange', (descriptor: avSession.AVSessionDescriptor) => {
683  console.info(`on topSessionChange : isActive : ${descriptor.isActive}`);
684  console.info(`on topSessionChange : type : ${descriptor.type}`);
685  console.info(`on topSessionChange : sessionTag : ${descriptor.sessionTag}`);
686});
687```
688
689## avSession.off('sessionCreate')
690
691off(type: 'sessionCreate', callback?: (session: AVSessionDescriptor) => void): void
692
693Unsubscribes from session creation events.
694
695**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
696
697**System capability**: SystemCapability.Multimedia.AVSession.Manager
698
699**System API**: This is a system API.
700
701**Parameters**
702
703| Name  | Type      | Mandatory| Description      |
704| -------- | ----------| ---- | ----------|
705| type     | string    | Yes  | Event type, which is **'sessionCreate'** in this case.|
706| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | No  | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **session** parameter in the callback describes a media session. The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                              |
707
708**Error codes**
709
710For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
711
712| ID| Error Message|
713| -------- | ---------------------------------------- |
714| 6600101  | Session service exception. |
715
716**Example**
717
718```ts
719avSession.off('sessionCreate');
720```
721
722## avSession.off('sessionDestroy')
723
724off(type: 'sessionDestroy', callback?: (session: AVSessionDescriptor) => void): void
725
726Unsubscribes from session destruction events.
727
728**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
729
730**System capability**: SystemCapability.Multimedia.AVSession.Manager
731
732**System API**: This is a system API.
733
734**Parameters**
735
736| Name  | Type       | Mandatory| Description                     |
737| -------- | -----------| ---- | -------------------------|
738| type     | string     | Yes  | Event type, which is **'sessionDestroy'** in this case.|
739| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | No  | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **session** parameter in the callback describes a media session. The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.|
740
741**Error codes**
742
743For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
744
745| ID| Error Message|
746| -------- | ---------------------------------------- |
747| 6600101  | Session service exception. |
748
749**Example**
750
751```ts
752avSession.off('sessionDestroy');
753```
754
755## avSession.off('topSessionChange')
756
757off(type: 'topSessionChange', callback?: (session: AVSessionDescriptor) => void): void
758
759Unsubscribes from top session change events.
760
761**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
762
763**System capability**: SystemCapability.Multimedia.AVSession.Manager
764
765**System API**: This is a system API.
766
767**Parameters**
768
769| Name  | Type             | Mandatory| Description                       |
770| -------- | -----------------| ---- | ---------------------------- |
771| type     | string           | Yes  | Event type, which is **'topSessionChange'** in this case.|
772| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | No  | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **session** parameter in the callback describes a media session. The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.|
773
774**Error codes**
775
776For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
777
778| ID| Error Message|
779| -------- | ---------------------------------------- |
780| 6600101  | Session service exception. |
781
782**Example**
783
784```ts
785avSession.off('topSessionChange');
786```
787
788## avSession.on('sessionServiceDie')
789
790on(type: 'sessionServiceDie', callback: () => void): void
791
792Subscribes to session service death events. Upon receiving this event, the application can clear resources.
793
794**System capability**: SystemCapability.Multimedia.AVSession.Core
795
796**System API**: This is a system API.
797
798**Parameters**
799
800| Name  | Type                | Mandatory| Description                                                        |
801| -------- | -------------------- | ---- | ------------------------------------------------------------ |
802| type     | string               | Yes  | Event type. The event **'sessionServiceDie'** is triggered when the session service dies.|
803| callback | callback: () => void | Yes  | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object.                               |
804
805**Error codes**
806
807For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
808
809| ID| Error Message|
810| -------- | ---------------------------------------- |
811| 6600101  | Session service exception. |
812
813**Example**
814
815```ts
816avSession.on('sessionServiceDie', () => {
817  console.info(`on sessionServiceDie  : session is  Died `);
818});
819```
820
821## avSession.off('sessionServiceDie')
822
823off(type: 'sessionServiceDie', callback?: () => void): void
824
825Unsubscribes from session service death events.
826
827**System capability**: SystemCapability.Multimedia.AVSession.Core
828
829**System API**: This is a system API.
830
831**Parameters**
832
833| Name   | Type                   | Mandatory |      Description                                              |
834| ------   | ---------------------- | ---- | ------------------------------------------------------- |
835| type     | string                 | Yes   | Event type. The event **'sessionServiceDie'** is triggered when the session service dies.|
836| callback | callback: () => void   | No   | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.           |
837
838**Error codes**
839
840For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
841
842| ID| Error Message|
843| -------- | ---------------------------------------- |
844| 6600101  | Session service exception. |
845
846**Example**
847
848```ts
849avSession.off('sessionServiceDie');
850```
851
852## avSession.sendSystemAVKeyEvent
853
854sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback\<void>): void
855
856Sends a system key event to the top session. This API uses an asynchronous callback to return the result.
857
858**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
859
860**System capability**: SystemCapability.Multimedia.AVSession.Manager
861
862**System API**: This is a system API.
863
864**Parameters**
865
866| Name  | Type                                                        | Mandatory| Description                                 |
867| -------- | ------------------------------------------------------------ | ---- | ------------------------------------- |
868| event    | [KeyEvent](js-apis-keyevent.md) | Yes  | Key event.                           |
869| callback | AsyncCallback\<void>                                         | Yes  | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.|
870
871**Error codes**
872
873For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
874
875| ID| Error Message|
876| -------- | ---------------------------------------- |
877| 6600101  | Session service exception. |
878| 6600105  | Invalid session command. |
879
880**Example**
881
882```ts
883import keyEvent from '@ohos.multimodalInput.keyEvent';
884import { BusinessError } from '@ohos.base';
885
886let keyItem: keyEvent.Key = {code:0x49, pressedTime:2, deviceId:0};
887let event: keyEvent.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};
888
889avSession.sendSystemAVKeyEvent(event, (err: BusinessError) => {
890  if (err) {
891    console.error(`SendSystemAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`);
892  } else {
893    console.info(`SendSystemAVKeyEvent : SUCCESS `);
894  }
895});
896```
897
898## avSession.sendSystemAVKeyEvent
899
900sendSystemAVKeyEvent(event: KeyEvent): Promise\<void>
901
902Sends a system key event to the top session. This API uses a promise to return the result.
903
904**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
905
906**System capability**: SystemCapability.Multimedia.AVSession.Manager
907
908**System API**: This is a system API.
909
910**Parameters**
911
912| Name| Type                           | Mandatory| Description      |
913| ------ | ------------------------------- | ---- | ---------- |
914| event  | [KeyEvent](js-apis-keyevent.md) | Yes  | Key event.|
915
916**Return value**
917
918| Type          | Description                         |
919| -------------- | ----------------------------- |
920| Promise\<void> | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.|
921
922**Error codes**
923
924For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
925
926| ID| Error Message|
927| -------- | ---------------------------------------- |
928| 6600101  | Session service exception. |
929| 6600105  | Invalid session command. |
930
931**Example**
932
933```ts
934import keyEvent from '@ohos.multimodalInput.keyEvent';
935import { BusinessError } from '@ohos.base';
936
937let keyItem: keyEvent.Key = {code:0x49, pressedTime:2, deviceId:0};
938let event: keyEvent.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};
939
940avSession.sendSystemAVKeyEvent(event).then(() => {
941  console.info(`SendSystemAVKeyEvent Successfully`);
942}).catch((err: BusinessError) => {
943  console.error(`SendSystemAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`);
944});
945```
946
947## avSession.sendSystemControlCommand
948
949sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback\<void>): void
950
951Sends a system control command to the top session. This API uses an asynchronous callback to return the result.
952
953**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
954
955**System capability**: SystemCapability.Multimedia.AVSession.Manager
956
957**System API**: This is a system API.
958
959**Parameters**
960
961| Name  | Type                                 | Mandatory| Description                                 |
962| -------- | ------------------------------------- | ---- | ------------------------------------- |
963| command  | [AVControlCommand](#avcontrolcommand10) | Yes  | Command to send.  |
964| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object.|
965
966**Error codes**
967
968For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
969
970| ID| Error Message|
971| -------- | ---------------------------------------- |
972| 6600101  | Session service exception. |
973| 6600105  | Invalid session command. |
974| 6600107  | Too many commands or events. |
975
976**Example**
977
978```ts
979import avSession from '@ohos.multimedia.avsession';
980
981let cmd : avSession.AVControlCommandType = 'play';
982// let cmd : avSession.AVControlCommandType = 'pause';
983// let cmd : avSession.AVControlCommandType = 'stop';
984// let cmd : avSession.AVControlCommandType = 'playNext';
985// let cmd : avSession.AVControlCommandType = 'playPrevious';
986// let cmd : avSession.AVControlCommandType = 'fastForward';
987// let cmd : avSession.AVControlCommandType = 'rewind';
988let avcommand: avSession.AVControlCommand = {command:cmd};
989// let cmd : avSession.AVControlCommandType = 'seek';
990// let avcommand = {command:cmd, parameter:10};
991// let cmd : avSession.AVControlCommandType = 'setSpeed';
992// let avcommand = {command:cmd, parameter:2.6};
993// let cmd : avSession.AVControlCommandType = 'setLoopMode';
994// let avcommand = {command:cmd, parameter:avSession.LoopMode.LOOP_MODE_SINGLE};
995// let cmd : avSession.AVControlCommandType = 'toggleFavorite';
996// let avcommand = {command:cmd, parameter:"false"};
997avSession.sendSystemControlCommand(avcommand, (err) => {
998  if (err) {
999    console.error(`SendSystemControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
1000  } else {
1001    console.info(`sendSystemControlCommand successfully`);
1002  }
1003});
1004```
1005
1006## avSession.sendSystemControlCommand
1007
1008sendSystemControlCommand(command: AVControlCommand): Promise\<void>
1009
1010Sends a system control command to the top session. This API uses a promise to return the result.
1011
1012**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
1013
1014**System capability**: SystemCapability.Multimedia.AVSession.Manager
1015
1016**System API**: This is a system API.
1017
1018**Parameters**
1019
1020| Name | Type                                 | Mandatory| Description                               |
1021| ------- | ------------------------------------- | ---- | ----------------------------------- |
1022| command | [AVControlCommand](#avcontrolcommand10) | Yes  | Command to send.|
1023
1024**Return value**
1025
1026| Type          | Description                         |
1027| -------------- | ----------------------------- |
1028| Promise\<void> | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.|
1029
1030**Error codes**
1031
1032For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
1033
1034| ID| Error Message|
1035| -------- | ---------------------------------------- |
1036| 6600101  | Session service exception. |
1037| 6600105  | Invalid session command. |
1038| 6600107  | Too many commands or events. |
1039
1040**Example**
1041
1042```ts
1043import avSession from '@ohos.multimedia.avsession';
1044import { BusinessError } from '@ohos.base';
1045
1046let cmd : avSession.AVControlCommandType = 'play';
1047// let cmd : avSession.AVControlCommandType = 'pause';
1048// let cmd : avSession.AVControlCommandType = 'stop';
1049// let cmd : avSession.AVControlCommandType = 'playNext';
1050// let cmd : avSession.AVControlCommandType = 'playPrevious';
1051// let cmd : avSession.AVControlCommandType = 'fastForward';
1052// let cmd : avSession.AVControlCommandType = 'rewind';
1053let avcommand: avSession.AVControlCommand = {command:cmd};
1054// let cmd : avSession.AVControlCommandType = 'seek';
1055// let avcommand = {command:cmd, parameter:10};
1056// let cmd : avSession.AVControlCommandType = 'setSpeed';
1057// let avcommand = {command:cmd, parameter:2.6};
1058// let cmd : avSession.AVControlCommandType = 'setLoopMode';
1059// let avcommand = {command:cmd, parameter:avSession.LoopMode.LOOP_MODE_SINGLE};
1060// let cmd : avSession.AVControlCommandType = 'toggleFavorite';
1061// let avcommand = {command:cmd, parameter:"false"};
1062avSession.sendSystemControlCommand(avcommand).then(() => {
1063  console.info(`SendSystemControlCommand successfully`);
1064}).catch((err: BusinessError) => {
1065  console.error(`SendSystemControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
1066});
1067```
1068
1069## ProtocolType<sup>10+</sup>
1070
1071Enumerates the protocol types supported by the remote device.
1072
1073**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1074
1075**System API**: This is a system API.
1076
1077| Name                       | Value  | Description        |
1078| --------------------------- | ---- | ----------- |
1079| TYPE_LOCAL      | 0    | Local device, which can be the built-in speaker or audio jack of the device, or an A2DP device.|
1080| TYPE_CAST_PLUS_MIRROR      | 1    | Cast+ mirror mode.|
1081| TYPE_CAST_PLUS_STREAM      | 2    | Cast+ stream mode, indicating that the media asset is being displayed on another device.|
1082
1083## avSession.startCastDeviceDiscovery<sup>10+</sup>
1084
1085startCastDeviceDiscovery(callback: AsyncCallback\<void>): void
1086
1087Starts cast-enabled device discovery. This API uses an asynchronous callback to return the result.
1088
1089**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1090
1091**System API**: This is a system API.
1092
1093**Parameters**
1094
1095| Name  | Type                                 | Mandatory| Description                                 |
1096| -------- | ------------------------------------- | ---- | ------------------------------------- |
1097| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If the command is sent and device discovery starts, **err** is **undefined**; otherwise, **err** is an error object.|
1098
1099
1100**Example**
1101
1102```ts
1103import { BusinessError } from '@ohos.base';
1104
1105avSession.startCastDeviceDiscovery((err: BusinessError) => {
1106  if (err) {
1107    console.error(`startCastDeviceDiscovery BusinessError: code: ${err.code}, message: ${err.message}`);
1108  } else {
1109    console.info(`startCastDeviceDiscovery successfully`);
1110  }
1111});
1112```
1113
1114## avSession.startCastDeviceDiscovery<sup>10+</sup>
1115
1116startCastDeviceDiscovery(filter: number, callback: AsyncCallback\<void>): void
1117
1118Starts cast-enabled device discovery with filter criteria specified. This API uses an asynchronous callback to return the result.
1119
1120**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1121
1122**System API**: This is a system API.
1123
1124**Parameters**
1125
1126| Name  | Type                                 | Mandatory| Description                                 |
1127| -------- | ------------------------------------- | ---- | ------------------------------------- |
1128| filter | number | Yes| Filter criteria for device discovery. The value consists of **ProtocolType**s.|
1129| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If the command is sent and device discovery starts, **err** is **undefined**; otherwise, **err** is an error object.|
1130
1131
1132**Example**
1133
1134```ts
1135import { BusinessError } from '@ohos.base';
1136
1137let filter = 2;
1138avSession.startCastDeviceDiscovery(filter, (err: BusinessError) => {
1139  if (err) {
1140    console.error(`startCastDeviceDiscovery BusinessError: code: ${err.code}, message: ${err.message}`);
1141  } else {
1142    console.info(`startCastDeviceDiscovery successfully`);
1143  }
1144});
1145```
1146
1147## avSession.startCastDeviceDiscovery<sup>10+</sup>
1148
1149startCastDeviceDiscovery(filter?: number): Promise\<void>
1150
1151Starts cast-enabled device discovery. This API uses a promise to return the result.
1152
1153**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1154
1155**System API**: This is a system API.
1156
1157**Parameters**
1158
1159| Name  | Type                                 | Mandatory| Description                                 |
1160| -------- | ------------------------------------- | ---- | ------------------------------------- |
1161| filter | number | No| Filter criteria for device discovery. The value consists of **ProtocolType**s.|
1162
1163**Return value**
1164
1165| Type          | Description                         |
1166| -------------- | ----------------------------- |
1167| Promise\<void> | Promise used to return the result. If the command is sent and device discovery starts, no value is returned; otherwise, an error object is returned.|
1168
1169**Example**
1170
1171```ts
1172import { BusinessError } from '@ohos.base';
1173
1174let filter = 2;
1175avSession.startCastDeviceDiscovery(filter).then(() => {
1176  console.info(`startCastDeviceDiscovery successfully`);
1177}).catch((err: BusinessError) => {
1178  console.error(`startCastDeviceDiscovery BusinessError: code: ${err.code}, message: ${err.message}`);
1179});
1180```
1181
1182## avSession.stopCastDeviceDiscovery<sup>10+</sup>
1183
1184stopCastDeviceDiscovery(callback: AsyncCallback\<void>): void
1185
1186Stops cast-enabled device discovery. This API uses an asynchronous callback to return the result.
1187
1188**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1189
1190**System API**: This is a system API.
1191
1192**Parameters**
1193
1194| Name  | Type                                 | Mandatory| Description                                 |
1195| -------- | ------------------------------------- | ---- | ------------------------------------- |
1196| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If device discovery stops, **err** is **undefined**; otherwise, **err** is an error object.|
1197
1198
1199**Example**
1200
1201```ts
1202import { BusinessError } from '@ohos.base';
1203
1204avSession.stopCastDeviceDiscovery((err: BusinessError) => {
1205  if (err) {
1206    console.error(`stopCastDeviceDiscovery BusinessError: code: ${err.code}, message: ${err.message}`);
1207  } else {
1208    console.info(`stopCastDeviceDiscovery successfully`);
1209  }
1210});
1211```
1212
1213## avSession.stopCastDeviceDiscovery<sup>10+</sup>
1214
1215stopCastDeviceDiscovery(): Promise\<void>
1216
1217Stops cast-enabled device discovery. This API uses a promise to return the result.
1218
1219**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1220
1221**System API**: This is a system API.
1222
1223**Return value**
1224
1225| Type          | Description                         |
1226| -------------- | ----------------------------- |
1227| Promise\<void> | Promise used to return the result. If device discovery stops, no value is returned; otherwise, an error object is returned.|
1228
1229**Example**
1230
1231```ts
1232import { BusinessError } from '@ohos.base';
1233
1234avSession.stopCastDeviceDiscovery().then(() => {
1235  console.info(`stopCastDeviceDiscovery successfully`);
1236}).catch((err: BusinessError) => {
1237  console.error(`stopCastDeviceDiscovery BusinessError: code: ${err.code}, message: ${err.message}`);
1238});
1239```
1240
1241## avSession.setDiscoverable<sup>10+</sup>
1242
1243setDiscoverable(enable: boolean, callback: AsyncCallback\<void>): void
1244
1245Sets whether to allow the device discoverable. A discoverable device can be used as the cast receiver. This API uses an asynchronous callback to return the result.
1246
1247**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1248
1249**System API**: This is a system API.
1250
1251**Parameters**
1252
1253| Name  | Type                                 | Mandatory| Description                                 |
1254| -------- | ------------------------------------- | ---- | ------------------------------------- |
1255| enable | boolean | Yes| Whether to allow the device discoverable. The value **true** means to allow the device discoverable, and **false** means the opposite.|
1256| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.|
1257
1258
1259**Example**
1260
1261```ts
1262import { BusinessError } from '@ohos.base';
1263
1264avSession.setDiscoverable(true, (err: BusinessError) => {
1265  if (err) {
1266    console.error(`setDiscoverable BusinessError: code: ${err.code}, message: ${err.message}`);
1267  } else {
1268    console.info(`setDiscoverable successfully`);
1269  }
1270});
1271```
1272
1273## avSession.setDiscoverable<sup>10+</sup>
1274
1275setDiscoverable(enable: boolean): Promise\<void>
1276
1277Sets whether to allow the device discoverable. A discoverable device can be used as the cast receiver. This API uses a promise to return the result.
1278
1279**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1280
1281**System API**: This is a system API.
1282
1283**Parameters**
1284
1285| Name  | Type                                 | Mandatory| Description                                 |
1286| -------- | ------------------------------------- | ---- | ------------------------------------- |
1287| enable | boolean | Yes| Whether to allow the device discoverable. The value **true** means to allow the device discoverable, and **false** means the opposite.|
1288
1289**Return value**
1290
1291| Type          | Description                         |
1292| -------------- | ----------------------------- |
1293| Promise\<void> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
1294
1295**Example**
1296
1297```ts
1298import { BusinessError } from '@ohos.base';
1299
1300avSession.setDiscoverable(true).then(() => {
1301  console.info(`setDiscoverable successfully`);
1302}).catch((err: BusinessError) => {
1303  console.error(`setDiscoverable BusinessError: code: ${err.code}, message: ${err.message}`);
1304});
1305```
1306
1307## avSession.on('deviceAvailable')<sup>10+</sup>
1308
1309on(type: 'deviceAvailable', callback: (device: OutputDeviceInfo) => void): void
1310
1311Subscribes to device discovery events.
1312
1313**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1314
1315**System API**: This is a system API.
1316
1317**Parameters**
1318
1319| Name  | Type                | Mandatory| Description                                                        |
1320| -------- | -------------------- | ---- | ------------------------------------------------------------ |
1321| type     | string               | Yes  | Event type. The event **'deviceAvailable'** is triggered when a device is discovered.|
1322| callback | (device: OutputDeviceInfo) => void | Yes  | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object.                               |
1323
1324**Example**
1325
1326```ts
1327import avSession from '@ohos.multimedia.avsession';
1328
1329let castDevice: avSession.OutputDeviceInfo;
1330avSession.on('deviceAvailable', (device: avSession.OutputDeviceInfo) => {
1331  castDevice = device;
1332  console.info(`on deviceAvailable  : ${device} `);
1333});
1334```
1335
1336## avSession.off('deviceAvailable')<sup>10+</sup>
1337
1338off(type: 'deviceAvailable', callback?: (device: OutputDeviceInfo) => void): void
1339
1340Unsubscribes from device discovery events.
1341
1342**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1343
1344**System API**: This is a system API.
1345
1346**Parameters**
1347
1348| Name   | Type                   | Mandatory |      Description                                              |
1349| ------   | ---------------------- | ---- | ------------------------------------------------------- |
1350| type     | string                 | Yes   | Event type. The event **'deviceAvailable'** is triggered when a device is discovered.|
1351| callback     | function                 | No   | Callback used to return the device information.|
1352
1353**Example**
1354
1355```ts
1356avSession.off('deviceAvailable');
1357```
1358
1359## avSession.on('deviceOffline')<sup>11+</sup>
1360
1361on(type: 'deviceOffline', callback: (deviceId: string) => void): void
1362
1363Subscribes to device offline events.
1364
1365**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1366
1367**System API**: This is a system API.
1368
1369**Parameters**
1370
1371| Name  | Type                | Mandatory| Description                                                        |
1372| -------- | -------------------- | ---- | ------------------------------------------------------------ |
1373| type     | string               | Yes  | Event type. The event **'deviceOffline'** is triggered when a device gets offline.|
1374| callback | (deviceId: string) => void | Yes  | Callback used to return the result. The **deviceId** parameter in the callback indicates the device ID. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. |
1375
1376**Example**
1377
1378```ts
1379import avSession from '@ohos.multimedia.avsession';
1380
1381let castDeviceId: string;
1382avSession.on('deviceOffline', (deviceId: string) => {
1383  castDeviceId = deviceId;
1384  console.info(`on deviceOffline  : ${deviceId} `);
1385});
1386```
1387
1388## avSession.off('deviceOffline')<sup>11+</sup>
1389
1390off(type: 'deviceOffline', callback?: (deviceId: string) => void): void
1391
1392Unsubscribes from device offline events.
1393
1394**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1395
1396**System API**: This is a system API.
1397
1398**Parameters**
1399
1400| Name   | Type                   | Mandatory |      Description                                              |
1401| ------   | ---------------------- | ---- | ------------------------------------------------------- |
1402| type     | string                 | Yes   | Event type, which is **'deviceOffline'** in this case.|
1403| callback | (deviceId: string) => void | No  | Callback used to return the result. The **deviceId** parameter in the callback indicates the device ID. 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.|
1404
1405**Example**
1406
1407```ts
1408avSession.off('deviceOffline');
1409```
1410
1411## avSession.getAVCastController<sup>10+</sup>
1412
1413getAVCastController(sessionId: string, callback: AsyncCallback\<AVCastController>): void
1414
1415Obtains the cast controller when a casting connection is set up. This API uses an asynchronous callback to return the result.
1416
1417This API can be called on both the local and remote devices. You can use the API to obtain the same controller to control audio playback after cast.
1418
1419**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1420
1421**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
1422
1423**System API**: This is a system API.
1424
1425**Parameters**
1426
1427| Name   | Type                                                       | Mandatory| Description                                                        |
1428| --------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
1429| sessionId | string                    | Yes  |Session ID.|
1430| callback  | AsyncCallback<[AVCastController](#avcastcontroller10)\> | Yes  | Callback used to return the cast controller.|
1431
1432**Error codes**
1433
1434For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
1435
1436| ID| Error Message|
1437| -------- | ---------------------------------------- |
1438| 6600101  | Session service exception |
1439| 6600102  | session does not exist |
1440
1441**Example**
1442
1443```ts
1444import { BusinessError } from '@ohos.base';
1445
1446let currentAVSession: avSession.AVSession | undefined = undefined;
1447let tag = "createNewSession";
1448let context: Context = getContext(this);
1449let sessionId: string = "";  // Used as an input parameter of subsequent functions.
1450
1451avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
1452  if (err) {
1453    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
1454  } else {
1455    currentAVSession = data;
1456    if (currentAVSession !== undefined) {
1457      sessionId = currentAVSession.sessionId;
1458    }
1459    console.info(`CreateAVSession : SUCCESS : sessionId = ${sessionId}`);
1460  }
1461});
1462
1463let aVCastController: avSession.AVCastController;
1464avSession.getAVCastController(sessionId , (err: BusinessError, avcontroller: avSession.AVCastController) => {
1465  if (err) {
1466    console.error(`getAVCastController BusinessError: code: ${err.code}, message: ${err.message}`);
1467  } else {
1468    aVCastController = avcontroller;
1469    console.info('getAVCastController : SUCCESS ');
1470  }
1471});
1472```
1473
1474## avSession.getAVCastController<sup>10+</sup>
1475
1476getAVCastController(sessionId: string): Promise\<AVCastController>
1477
1478Obtains the cast controller when a casting connection is set up. This API uses a promise to return the result.
1479
1480This API can be called on both the local and remote devices. You can use the API to obtain the same controller to control audio playback after cast.
1481
1482**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1483
1484**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
1485
1486**System API**: This is a system API.
1487
1488**Parameters**
1489
1490| Name   | Type                      | Mandatory| Description                                                        |
1491| --------- | ------------------------- | ---- | ------------------------------------------------------------ |
1492| sessionId | string                    | Yes  |Session ID.|
1493
1494**Return value**
1495
1496| Type                                                       | Description            |
1497| --------- | ------------------------------------------------------------ |
1498| Promise<[AVCastController](#avcastcontroller10)\>  | Promise used to return the cast controller.|
1499
1500**Error codes**
1501
1502For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
1503
1504| ID| Error Message|
1505| -------- | ---------------------------------------- |
1506| 6600101  | server exception |
1507| 6600102  | The session does not exist |
1508
1509**Example**
1510
1511```ts
1512import { BusinessError } from '@ohos.base';
1513
1514let currentAVSession: avSession.AVSession | undefined = undefined;
1515let tag = "createNewSession";
1516let context: Context = getContext(this);
1517let sessionId: string = "";  // Used as an input parameter of subsequent functions.
1518
1519avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
1520  if (err) {
1521    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
1522  } else {
1523    currentAVSession = data;
1524    if (currentAVSession !== undefined) {
1525      sessionId = currentAVSession.sessionId;
1526    }
1527    console.info(`CreateAVSession : SUCCESS : sessionId = ${sessionId}`);
1528  }
1529});
1530
1531let aVCastController: avSession.AVCastController;
1532avSession.getAVCastController(sessionId).then((avcontroller: avSession.AVCastController) => {
1533  aVCastController = avcontroller;
1534  console.info('getAVCastController : SUCCESS');
1535}).catch((err: BusinessError) => {
1536  console.error(`getAVCastController BusinessError: code: ${err.code}, message: ${err.message}`);
1537});
1538```
1539
1540## avSession.startCasting<sup>10+</sup>
1541
1542startCasting(session: SessionToken, device: OutputDeviceInfo, callback: AsyncCallback\<void>): void
1543
1544Starts casting. This API uses an asynchronous callback to return the result.
1545
1546**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
1547
1548**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1549
1550**System API**: This is a system API.
1551
1552**Parameters**
1553
1554| Name  | Type                                 | Mandatory| Description                                 |
1555| -------- | ------------------------------------- | ---- | ------------------------------------- |
1556| session      | [SessionToken](#sessiontoken) | Yes  | Session token.  |
1557| device | [OutputDeviceInfo](#outputdeviceinfo10)                        | Yes  | Device-related information.|
1558| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If the command is sent and casting starts, **err** is **undefined**; otherwise, **err** is an error object.|
1559
1560**Error codes**
1561
1562For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
1563
1564| ID| Error Message|
1565| -------- | ---------------------------------------- |
1566| 6600101  | Session service exception. |
1567| 6600108 | Device connecting failed.       |
1568
1569**Example**
1570
1571```ts
1572import avSession from '@ohos.multimedia.avsession';
1573import { BusinessError } from '@ohos.base';
1574
1575let currentAVSession: avSession.AVSession | undefined = undefined;
1576let tag = "createNewSession";
1577let context: Context = getContext(this);
1578let sessionId: string = "";  // Used as an input parameter of subsequent functions.
1579
1580avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
1581  if (err) {
1582    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
1583  } else {
1584    currentAVSession = data;
1585    if (currentAVSession !== undefined) {
1586      sessionId = currentAVSession.sessionId;
1587    }
1588    console.info(`CreateAVSession : SUCCESS : sessionId = ${sessionId}`);
1589  }
1590});
1591
1592let myToken: avSession.SessionToken = {
1593  sessionId: sessionId,
1594}
1595let castDevice: avSession.OutputDeviceInfo | undefined = undefined;
1596avSession.on('deviceAvailable', (device: avSession.OutputDeviceInfo) => {
1597  castDevice = device;
1598  console.info(`on deviceAvailable  : ${device} `);
1599});
1600if (castDevice !== undefined) {
1601  avSession.startCasting(myToken, castDevice, (err: BusinessError) => {
1602    if (err) {
1603      console.error(`startCasting BusinessError: code: ${err.code}, message: ${err.message}`);
1604    } else {
1605      console.info(`startCasting successfully`);
1606    }
1607  });
1608}
1609```
1610
1611## avSession.startCasting<sup>10+</sup>
1612
1613startCasting(session: SessionToken, device: OutputDeviceInfo): Promise\<void>
1614
1615Starts casting. This API uses a promise to return the result.
1616
1617**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
1618
1619**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1620
1621**System API**: This is a system API.
1622
1623**Parameters**
1624
1625| Name  | Type                                 | Mandatory| Description                                 |
1626| -------- | ------------------------------------- | ---- | ------------------------------------- |
1627| session      | [SessionToken](#sessiontoken) | Yes  | Session token.  |
1628| device | [OutputDeviceInfo](#outputdeviceinfo10)                        | Yes  | Device-related information.|
1629
1630**Return value**
1631
1632| Type          | Description                         |
1633| -------------- | ----------------------------- |
1634| Promise\<void> | Promise used to return the result. If the command is sent and casting starts, no value is returned; otherwise, an error object is returned.|
1635
1636**Error codes**
1637
1638For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
1639
1640| ID| Error Message|
1641| -------- | ---------------------------------------- |
1642| 6600101  | Session service exception. |
1643| 6600108 | Device connecting failed.       |
1644
1645**Example**
1646
1647```ts
1648import avSession from '@ohos.multimedia.avsession';
1649import { BusinessError } from '@ohos.base';
1650
1651let currentAVSession: avSession.AVSession | undefined = undefined;
1652let tag = "createNewSession";
1653let context: Context = getContext(this);
1654let sessionId: string = "";  // Used as an input parameter of subsequent functions.
1655
1656avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
1657  if (err) {
1658    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
1659  } else {
1660    currentAVSession = data;
1661    if (currentAVSession !== undefined) {
1662      sessionId = currentAVSession.sessionId;
1663    }
1664    console.info(`CreateAVSession : SUCCESS : sessionId = ${sessionId}`);
1665  }
1666});
1667
1668let myToken: avSession.SessionToken = {
1669  sessionId: sessionId,
1670}
1671let castDevice: avSession.OutputDeviceInfo | undefined = undefined;
1672avSession.on('deviceAvailable', (device: avSession.OutputDeviceInfo) => {
1673  castDevice = device;
1674  console.info(`on deviceAvailable  : ${device} `);
1675});
1676if (castDevice !== undefined) {
1677  avSession.startCasting(myToken, castDevice).then(() => {
1678    console.info(`startCasting successfully`);
1679  }).catch((err: BusinessError) => {
1680    console.error(`startCasting BusinessError: code: ${err.code}, message: ${err.message}`);
1681  });
1682}
1683```
1684
1685## avSession.stopCasting<sup>10+</sup>
1686
1687stopCasting(session: SessionToken, callback: AsyncCallback\<void>): void
1688
1689Stops castings. This API uses an asynchronous callback to return the result.
1690
1691**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1692
1693**System API**: This is a system API.
1694
1695**Parameters**
1696
1697| Name  | Type                                 | Mandatory| Description                                 |
1698| -------- | ------------------------------------- | ---- | ------------------------------------- |
1699| session      | [SessionToken](#sessiontoken) | Yes  | Session token.  |
1700| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If casting stops, **err** is **undefined**; otherwise, **err** is an error object.|
1701
1702**Error codes**
1703
1704For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
1705
1706| ID| Error Message|
1707| -------- | ---------------------------------------- |
1708| 6600109  | The remote connection is not established. |
1709
1710**Example**
1711
1712```ts
1713import avSession from '@ohos.multimedia.avsession';
1714import { BusinessError } from '@ohos.base';
1715
1716let currentAVSession: avSession.AVSession | undefined = undefined;
1717let tag = "createNewSession";
1718let context: Context = getContext(this);
1719let sessionId: string = "";  // Used as an input parameter of subsequent functions.
1720
1721avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
1722  if (err) {
1723    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
1724  } else {
1725    currentAVSession = data;
1726    if (currentAVSession !== undefined) {
1727      sessionId = currentAVSession.sessionId;
1728    }
1729    console.info(`CreateAVSession : SUCCESS : sessionId = ${sessionId}`);
1730  }
1731});
1732
1733let myToken: avSession.SessionToken = {
1734  sessionId: sessionId,
1735}
1736avSession.stopCasting(myToken, (err: BusinessError) => {
1737  if (err) {
1738    console.error(`stopCasting BusinessError: code: ${err.code}, message: ${err.message}`);
1739  } else {
1740    console.info(`stopCasting successfully`);
1741  }
1742});
1743```
1744
1745## avSession.stopCasting<sup>10+</sup>
1746
1747stopCasting(session: SessionToken): Promise\<void>
1748
1749Stops castings. This API uses a promise to return the result.
1750
1751**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1752
1753**System API**: This is a system API.
1754
1755**Parameters**
1756
1757| Name  | Type                                 | Mandatory| Description                                 |
1758| -------- | ------------------------------------- | ---- | ------------------------------------- |
1759| session      | [SessionToken](#sessiontoken) | Yes  | Session token.  |
1760
1761**Return value**
1762
1763| Type          | Description                         |
1764| -------------- | ----------------------------- |
1765| Promise\<void> | Promise used to return the result. If casting stops, no value is returned; otherwise, an error object is returned.|
1766
1767**Error codes**
1768
1769For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
1770
1771| ID| Error Message|
1772| -------- | ---------------------------------------- |
1773| 6600109  | The remote connection is not established. |
1774
1775**Example**
1776
1777```ts
1778import avSession from '@ohos.multimedia.avsession';
1779import { BusinessError } from '@ohos.base';
1780
1781let currentAVSession: avSession.AVSession | undefined = undefined;
1782let tag = "createNewSession";
1783let context: Context = getContext(this);
1784let sessionId: string = "";  // Used as an input parameter of subsequent functions.
1785
1786avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
1787  if (err) {
1788    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
1789  } else {
1790    currentAVSession = data;
1791    if (currentAVSession !== undefined) {
1792      sessionId = currentAVSession.sessionId;
1793    }
1794    console.info(`CreateAVSession : SUCCESS : sessionId = ${sessionId}`);
1795  }
1796});
1797
1798let myToken: avSession.SessionToken = {
1799  sessionId: sessionId,
1800}
1801avSession.stopCasting(myToken).then(() => {
1802  console.info(`stopCasting successfully`);
1803}).catch((err: BusinessError) => {
1804  console.error(`stopCasting BusinessError: code: ${err.code}, message: ${err.message}`);
1805});
1806
1807
1808```
1809
1810## AVSessionType<sup>10+<sup>
1811Enumerates the session types supported by the session.
1812
1813**System capability**: SystemCapability.Multimedia.AVSession.Core
1814
1815| Name | Type  | Description|
1816| ----- | ------ | ---- |
1817| audio | string | Audio session.|
1818| video | string | Video session.|
1819
1820## AVSession<sup>10+</sup>
1821
1822An **AVSession** object is created by calling [avSession.createAVSession](#avsessioncreateavsession10). The object enables you to obtain the session ID and set the metadata and playback state.
1823
1824### Attributes
1825
1826**System capability**: SystemCapability.Multimedia.AVSession.Core
1827
1828| Name     | Type  | Readable| Writable| Description                         |
1829| :-------- | :----- | :--- | :--- | :---------------------------- |
1830| sessionId | string | Yes  | No  | Unique session ID of the **AVSession** object.|
1831| sessionType<sup>10+</sup> | AVSessionType | Yes  | No  | AVSession type.|
1832
1833
1834**Example**
1835
1836```ts
1837import avSession from '@ohos.multimedia.avsession';
1838
1839let sessionId: string = currentAVSession.sessionId;
1840let sessionType: avSession.AVSessionType = currentAVSession.sessionType;
1841```
1842
1843### setAVMetadata<sup>10+</sup>
1844
1845setAVMetadata(data: AVMetadata): Promise\<void>
1846
1847Sets session metadata. This API uses a promise to return the result.
1848
1849**System capability**: SystemCapability.Multimedia.AVSession.Core
1850
1851**Parameters**
1852
1853| Name| Type                     | Mandatory| Description        |
1854| ------ | ------------------------- | ---- | ------------ |
1855| data   | [AVMetadata](#avmetadata10) | Yes  | Session metadata.|
1856
1857**Return value**
1858
1859| Type          | Description                         |
1860| -------------- | ----------------------------- |
1861| Promise\<void> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
1862
1863**Error codes**
1864
1865For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
1866
1867| ID| Error Message|
1868| -------- | ---------------------------------------- |
1869| 6600101  | Session service exception. |
1870| 6600102  | The session does not exist. |
1871
1872**Example**
1873
1874```ts
1875import avSession from '@ohos.multimedia.avsession';
1876import { BusinessError } from '@ohos.base';
1877
1878let metadata: avSession.AVMetadata = {
1879  assetId: "121278",
1880  title: "lose yourself",
1881  artist: "Eminem",
1882  author: "ST",
1883  album: "Slim shady",
1884  writer: "ST",
1885  composer: "ST",
1886  duration: 2222,
1887  mediaImage: "https://www.example.com/example.jpg",
1888  subtitle: "8 Mile",
1889  description: "Rap",
1890  lyric: "https://www.example.com/example.lrc",
1891  previousAssetId: "121277",
1892  nextAssetId: "121279",
1893};
1894currentAVSession.setAVMetadata(metadata).then(() => {
1895  console.info(`SetAVMetadata successfully`);
1896}).catch((err: BusinessError) => {
1897  console.error(`SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
1898});
1899```
1900
1901### setAVMetadata<sup>10+</sup>
1902
1903setAVMetadata(data: AVMetadata, callback: AsyncCallback\<void>): void
1904
1905Sets session metadata. This API uses an asynchronous callback to return the result.
1906
1907**System capability**: SystemCapability.Multimedia.AVSession.Core
1908
1909**Parameters**
1910
1911| Name  | Type                     | Mandatory| Description                                 |
1912| -------- | ------------------------- | ---- | ------------------------------------- |
1913| data     | [AVMetadata](#avmetadata10) | Yes  | Session metadata.                         |
1914| callback | AsyncCallback\<void>      | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.|
1915
1916**Error codes**
1917
1918For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
1919
1920| ID| Error Message|
1921| -------- | ---------------------------------------- |
1922| 6600101  | Session service exception. |
1923| 6600102  | The session does not exist. |
1924
1925**Example**
1926
1927```ts
1928import avSession from '@ohos.multimedia.avsession';
1929import { BusinessError } from '@ohos.base';
1930
1931let metadata: avSession.AVMetadata = {
1932  assetId: "121278",
1933  title: "lose yourself",
1934  artist: "Eminem",
1935  author: "ST",
1936  album: "Slim shady",
1937  writer: "ST",
1938  composer: "ST",
1939  duration: 2222,
1940  mediaImage: "https://www.example.com/example.jpg",
1941  subtitle: "8 Mile",
1942  description: "Rap",
1943  lyric: "https://www.example.com/example.lrc",
1944  previousAssetId: "121277",
1945  nextAssetId: "121279",
1946};
1947currentAVSession.setAVMetadata(metadata, (err: BusinessError) => {
1948  if (err) {
1949    console.error(`SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
1950  } else {
1951    console.info(`SetAVMetadata successfully`);
1952  }
1953});
1954```
1955
1956### setAVPlaybackState<sup>10+</sup>
1957
1958setAVPlaybackState(state: AVPlaybackState): Promise\<void>
1959
1960Sets information related to the session playback state. This API uses a promise to return the result.
1961
1962**System capability**: SystemCapability.Multimedia.AVSession.Core
1963
1964**Parameters**
1965
1966| Name| Type                               | Mandatory| Description                                          |
1967| ------ | ----------------------------------- | ---- | ---------------------------------------------- |
1968| state   | [AVPlaybackState](#avplaybackstate10) | Yes  | Information related to the session playback state.|
1969
1970**Return value**
1971
1972| Type          | Description                         |
1973| -------------- | ----------------------------- |
1974| Promise\<void> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
1975
1976**Error codes**
1977
1978For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
1979
1980| ID| Error Message|
1981| -------- | ---------------------------------------- |
1982| 6600101  | Session service exception. |
1983| 6600102  | The session does not exist. |
1984
1985**Example**
1986
1987```ts
1988import avSession from '@ohos.multimedia.avsession';
1989import { BusinessError } from '@ohos.base';
1990
1991let playbackState: avSession.AVPlaybackState = {
1992  state:avSession.PlaybackState.PLAYBACK_STATE_PLAY,
1993  speed: 1.0,
1994  position:{elapsedTime:10, updateTime:(new Date()).getTime()},
1995  bufferedTime:1000,
1996  loopMode:avSession.LoopMode.LOOP_MODE_SINGLE,
1997  isFavorite:true,
1998};
1999currentAVSession.setAVPlaybackState(playbackState).then(() => {
2000  console.info(`SetAVPlaybackState successfully`);
2001}).catch((err: BusinessError) => {
2002  console.error(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
2003});
2004```
2005
2006### setAVPlaybackState<sup>10+</sup>
2007
2008setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback\<void>): void
2009
2010Sets information related to the session playback state. This API uses an asynchronous callback to return the result.
2011
2012**System capability**: SystemCapability.Multimedia.AVSession.Core
2013
2014**Parameters**
2015
2016| Name  | Type                               | Mandatory| Description                                          |
2017| -------- | ----------------------------------- | ---- | ---------------------------------------------- |
2018| state     | [AVPlaybackState](#avplaybackstate10) | Yes  | Information related to the session playback state.|
2019| callback | AsyncCallback\<void>                | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.         |
2020
2021**Error codes**
2022
2023For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2024
2025| ID| Error Message|
2026| -------- | ---------------------------------------- |
2027| 6600101  | Session service exception. |
2028| 6600102  | The session does not exist. |
2029
2030**Example**
2031
2032```ts
2033import avSession from '@ohos.multimedia.avsession';
2034import { BusinessError } from '@ohos.base';
2035
2036let PlaybackState: avSession.AVPlaybackState = {
2037  state:avSession.PlaybackState.PLAYBACK_STATE_PLAY,
2038  speed: 1.0,
2039  position:{elapsedTime:10, updateTime:(new Date()).getTime()},
2040  bufferedTime:1000,
2041  loopMode:avSession.LoopMode.LOOP_MODE_SINGLE,
2042  isFavorite:true,
2043};
2044currentAVSession.setAVPlaybackState(PlaybackState, (err: BusinessError) => {
2045  if (err) {
2046    console.error(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
2047  } else {
2048    console.info(`SetAVPlaybackState successfully`);
2049  }
2050});
2051```
2052
2053### setLaunchAbility<sup>10+</sup>
2054
2055setLaunchAbility(ability: WantAgent): Promise\<void>
2056
2057Sets a launcher ability. This API uses a promise to return the result.
2058
2059**System capability**: SystemCapability.Multimedia.AVSession.Core
2060
2061**Parameters**
2062
2063| Name | Type                                         | Mandatory| Description                                                       |
2064| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- |
2065| ability | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes  | Application attributes, such as the bundle name, ability name, and deviceID.|
2066
2067**Return value**
2068
2069| Type          | Description                         |
2070| -------------- | ----------------------------- |
2071| Promise\<void> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
2072
2073**Error codes**
2074
2075For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2076
2077| ID| Error Message|
2078| -------- | ---------------------------------------- |
2079| 6600101  | Session service exception. |
2080| 6600102  | The session does not exist. |
2081
2082**Example**
2083
2084```ts
2085import wantAgent from '@ohos.app.ability.wantAgent';
2086import { BusinessError } from '@ohos.base';
2087
2088// WantAgentInfo object
2089let wantAgentInfo: wantAgent.WantAgentInfo = {
2090  wants: [
2091    {
2092      deviceId: "deviceId",
2093      bundleName: "com.example.myapplication",
2094      abilityName: "EntryAbility",
2095      action: "action1",
2096      entities: ["entity1"],
2097      type: "MIMETYPE",
2098      uri: "key={true,true,false}",
2099      parameters:
2100        {
2101          mykey0: 2222,
2102          mykey1: [1, 2, 3],
2103          mykey2: "[1, 2, 3]",
2104          mykey3: "ssssssssssssssssssssssssss",
2105          mykey4: [false, true, false],
2106          mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"],
2107          mykey6: true,
2108        }
2109    }
2110  ],
2111  operationType: wantAgent.OperationType.START_ABILITIES,
2112  requestCode: 0,
2113  wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
2114}
2115
2116wantAgent.getWantAgent(wantAgentInfo).then((agent) => {
2117  currentAVSession.setLaunchAbility(agent).then(() => {
2118    console.info(`SetLaunchAbility successfully`);
2119  }).catch((err: BusinessError) => {
2120    console.error(`SetLaunchAbility BusinessError: code: ${err.code}, message: ${err.message}`);
2121  });
2122});
2123```
2124
2125### setLaunchAbility<sup>10+</sup>
2126
2127setLaunchAbility(ability: WantAgent, callback: AsyncCallback\<void>): void
2128
2129Sets a launcher ability. This API uses an asynchronous callback to return the result.
2130
2131**System capability**: SystemCapability.Multimedia.AVSession.Core
2132
2133**Parameters**
2134
2135| Name  | Type                                         | Mandatory| Description                                                        |
2136| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
2137| ability  | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes  | Application attributes, such as the bundle name, ability name, and deviceID. |
2138| callback | AsyncCallback\<void>                          | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.|
2139
2140**Error codes**
2141
2142For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2143
2144| ID| Error Message|
2145| -------- | ---------------------------------------- |
2146| 6600101  | Session service exception. |
2147| 6600102  | The session does not exist. |
2148
2149**Example**
2150
2151```ts
2152import wantAgent from '@ohos.app.ability.wantAgent';
2153import { BusinessError } from '@ohos.base';
2154
2155// WantAgentInfo object
2156let wantAgentInfo: wantAgent.WantAgentInfo = {
2157  wants: [
2158    {
2159      deviceId: "deviceId",
2160      bundleName: "com.example.myapplication",
2161      abilityName: "EntryAbility",
2162      action: "action1",
2163      entities: ["entity1"],
2164      type: "MIMETYPE",
2165      uri: "key={true,true,false}",
2166      parameters:
2167        {
2168          mykey0: 2222,
2169          mykey1: [1, 2, 3],
2170          mykey2: "[1, 2, 3]",
2171          mykey3: "ssssssssssssssssssssssssss",
2172          mykey4: [false, true, false],
2173          mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"],
2174          mykey6: true,
2175        }
2176    }
2177  ],
2178  operationType: wantAgent.OperationType.START_ABILITIES,
2179  requestCode: 0,
2180  wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
2181}
2182
2183wantAgent.getWantAgent(wantAgentInfo).then((agent) => {
2184  currentAVSession.setLaunchAbility(agent, (err: BusinessError) => {
2185    if (err) {
2186      console.error(`SetLaunchAbility BusinessError: code: ${err.code}, message: ${err.message}`);
2187    } else {
2188      console.info(`SetLaunchAbility successfully`);
2189    }
2190  });
2191});
2192```
2193
2194### dispatchSessionEvent<sup>10+</sup>
2195
2196dispatchSessionEvent(event: string, args: {[key: string]: Object}): Promise\<void>
2197
2198Dispatches a custom event in the session, including the event name and event content in key-value pair format. This API uses a promise to return the result. It is called by the provider.
2199
2200**System capability**: SystemCapability.Multimedia.AVSession.Core
2201
2202**Parameters**
2203
2204| Name | Type                                         | Mandatory| Description                                                       |
2205| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- |
2206| event | string | Yes  | Name of the session event.|
2207| args | {[key: string]: any} | Yes  | Event content in key-value pair format.|
2208
2209> **NOTE**
2210>
2211> The **args** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want (Want)](./js-apis-app-ability-want.md).
2212
2213**Return value**
2214
2215| Type          | Description                         |
2216| -------------- | ----------------------------- |
2217| Promise\<void> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
2218
2219**Error codes**
2220
2221For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2222
2223| ID| Error Message|
2224| -------- | ---------------------------------------- |
2225| 6600101  | Session service exception. |
2226| 6600102  | The session does not exist. |
2227
2228**Example**
2229
2230```ts
2231import avSession from '@ohos.multimedia.avsession';
2232import { BusinessError } from '@ohos.base';
2233
2234let currentAVSession: avSession.AVSession | undefined = undefined;
2235let tag = "createNewSession";
2236let context: Context = getContext(this);
2237
2238avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
2239  if (err) {
2240    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
2241  } else {
2242    currentAVSession = data;
2243  }
2244});
2245let eventName = "dynamic_lyric";
2246if (currentAVSession !== undefined) {
2247  (currentAVSession as avSession.AVSession).dispatchSessionEvent(eventName, {lyric : "This is lyric"}).then(() => {
2248    console.info(`dispatchSessionEvent successfully`);
2249  }).catch((err: BusinessError) => {
2250    console.error(`dispatchSessionEvent BusinessError: code: ${err.code}, message: ${err.message}`);
2251  })
2252}
2253```
2254
2255### dispatchSessionEvent<sup>10+</sup>
2256
2257dispatchSessionEvent(event: string, args: {[key: string]: Object}, callback: AsyncCallback\<void>): void
2258
2259Dispatches a custom event in the session, including the event name and event content in key-value pair format. This API uses an asynchronous callback to return the result. It is called by the provider.
2260
2261**System capability**: SystemCapability.Multimedia.AVSession.Core
2262
2263**Parameters**
2264
2265| Name | Type                                         | Mandatory| Description                                                       |
2266| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- |
2267| event | string | Yes  | Name of the session event.|
2268| args | {[key: string]: any} | Yes  | Event content in key-value pair format.|
2269| callback | AsyncCallback\<void>                          | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.|
2270
2271> **NOTE**
2272>
2273> The **args** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want (Want)](./js-apis-app-ability-want.md).
2274
2275**Error codes**
2276
2277For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2278
2279| ID| Error Message|
2280| -------- | ---------------------------------------- |
2281| 6600101  | Session service exception. |
2282| 6600102  | The session does not exist. |
2283
2284**Example**
2285
2286```ts
2287import avSession from '@ohos.multimedia.avsession';
2288import { BusinessError } from '@ohos.base';
2289
2290let currentAVSession: avSession.AVSession | undefined = undefined;
2291let tag = "createNewSession";
2292let context: Context = getContext(this);
2293
2294avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
2295  if (err) {
2296    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
2297  } else {
2298    currentAVSession = data;
2299  }
2300});
2301let eventName: string = "dynamic_lyric";
2302if (currentAVSession !== undefined) {
2303  (currentAVSession as avSession.AVSession).dispatchSessionEvent(eventName, {lyric : "This is lyric"}, (err: BusinessError) => {
2304    if (err) {
2305      console.error(`dispatchSessionEvent BusinessError: code: ${err.code}, message: ${err.message}`);
2306    }
2307  })
2308}
2309```
2310
2311### setAVQueueItems<sup>10+</sup>
2312
2313setAVQueueItems(items: Array\<AVQueueItem>): Promise\<void>
2314
2315Sets a playlist. This API uses a promise to return the result.
2316
2317**System capability**: SystemCapability.Multimedia.AVSession.Core
2318
2319**Parameters**
2320
2321| Name | Type                                | Mandatory| Description                              |
2322| ------ | ------------------------------------ | ---- | ---------------------------------- |
2323| items  | Array<[AVQueueItem](#avqueueitem10)\> | Yes  | Playlist to set.|
2324
2325**Return value**
2326
2327| Type          | Description                         |
2328| -------------- | ----------------------------- |
2329| Promise\<void> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
2330
2331**Error codes**
2332
2333For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2334
2335| ID| Error Message|
2336| -------- | ---------------------------------------- |
2337| 6600101  | Session service exception. |
2338| 6600102  | The session does not exist. |
2339
2340**Example**
2341
2342```ts
2343import image from '@ohos.multimedia.image';
2344import resourceManager from '@ohos.resourceManager';
2345import { BusinessError } from '@ohos.base';
2346import avSession from '@ohos.multimedia.avsession';
2347
2348async function setAVQueueItems() {
2349  let value = await resourceManager.getSystemResourceManager().getRawFileContent('IMAGE_URI');
2350  let imageSource= await image.createImageSource(value.buffer);
2351  let imagePixel = await imageSource.createPixelMap({desiredSize:{width: 150, height: 150}});
2352  let queueItemDescription_1: avSession.AVMediaDescription = {
2353    assetId: '001',
2354    title: 'music_name',
2355    subtitle: 'music_sub_name',
2356    description: 'music_description',
2357    mediaImage : imagePixel,
2358    extras: {extras:'any'}
2359  };
2360  let queueItem_1: avSession.AVQueueItem = {
2361    itemId: 1,
2362    description: queueItemDescription_1
2363  };
2364  let queueItemDescription_2: avSession.AVMediaDescription = {
2365    assetId: '002',
2366    title: 'music_name',
2367    subtitle: 'music_sub_name',
2368    description: 'music_description',
2369    mediaImage: imagePixel,
2370    extras: {extras:'any'}
2371  };
2372  let queueItem_2: avSession.AVQueueItem = {
2373    itemId: 2,
2374    description: queueItemDescription_2
2375  };
2376  let queueItemsArray: avSession.AVQueueItem[] = [queueItem_1, queueItem_2];
2377  currentAVSession.setAVQueueItems(queueItemsArray).then(() => {
2378    console.info(`SetAVQueueItems successfully`);
2379  }).catch((err: BusinessError) => {
2380    console.error(`SetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`);
2381  });
2382}
2383```
2384
2385### setAVQueueItems<sup>10+</sup>
2386
2387setAVQueueItems(items: Array\<AVQueueItem>, callback: AsyncCallback\<void>): void
2388
2389Sets a playlist. This API uses an asynchronous callback to return the result.
2390
2391**System capability**: SystemCapability.Multimedia.AVSession.Core
2392
2393**Parameters**
2394
2395| Name  | Type                                 | Mandatory| Description                                                        |
2396| -------- | ------------------------------------ | ---- | ----------------------------------------------------------- |
2397| items    | Array<[AVQueueItem](#avqueueitem10)\> | Yes  | Playlist to set.                         |
2398| callback | AsyncCallback\<void>                 | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.|
2399
2400**Error codes**
2401
2402For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2403
2404| ID| Error Message|
2405| -------- | ---------------------------------------- |
2406| 6600101  | Session service exception. |
2407| 6600102  | The session does not exist. |
2408
2409**Example**
2410
2411```ts
2412import image from '@ohos.multimedia.image';
2413import resourceManager from '@ohos.resourceManager';
2414import { BusinessError } from '@ohos.base';
2415import avSession from '@ohos.multimedia.avsession';
2416
2417async function setAVQueueItems() {
2418  let value = await resourceManager.getSystemResourceManager().getRawFileContent('IMAGE_URI');
2419  let imageSource= await image.createImageSource(value.buffer);
2420  let imagePixel = await imageSource.createPixelMap({desiredSize:{width: 150, height: 150}});
2421  let queueItemDescription_1: avSession.AVMediaDescription = {
2422    assetId: '001',
2423    title: 'music_name',
2424    subtitle: 'music_sub_name',
2425    description: 'music_description',
2426    mediaImage : imagePixel,
2427    extras: {extras:'any'}
2428  };
2429  let queueItem_1: avSession.AVQueueItem = {
2430    itemId: 1,
2431    description: queueItemDescription_1
2432  };
2433  let queueItemDescription_2: avSession.AVMediaDescription = {
2434    assetId: '002',
2435    title: 'music_name',
2436    subtitle: 'music_sub_name',
2437    description: 'music_description',
2438    mediaImage: imagePixel,
2439    extras: {extras:'any'}
2440  };
2441  let queueItem_2: avSession.AVQueueItem = {
2442    itemId: 2,
2443    description: queueItemDescription_2
2444  };
2445  let queueItemsArray: avSession.AVQueueItem[] = [queueItem_1, queueItem_2];
2446  currentAVSession.setAVQueueItems(queueItemsArray, (err: BusinessError) => {
2447    if (err) {
2448      console.error(`SetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`);
2449    } else {
2450      console.info(`SetAVQueueItems successfully`);
2451    }
2452  });
2453}
2454```
2455
2456### setAVQueueTitle<sup>10+</sup>
2457
2458setAVQueueTitle(title: string): Promise\<void>
2459
2460Sets a name for the playlist. This API uses a promise to return the result.
2461
2462**System capability**: SystemCapability.Multimedia.AVSession.Core
2463
2464**Parameters**
2465
2466| Name | Type  | Mandatory| Description          |
2467| ------ | ------ | ---- | -------------- |
2468| title  | string | Yes  | Name of the playlist.|
2469
2470**Return value**
2471
2472| Type          | Description                         |
2473| -------------- | ----------------------------- |
2474| Promise\<void> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
2475
2476**Error codes**
2477
2478For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2479
2480| ID| Error Message|
2481| -------- | ---------------------------------------- |
2482| 6600101  | Session service exception. |
2483| 6600102  | The session does not exist. |
2484
2485**Example**
2486
2487```ts
2488import { BusinessError } from '@ohos.base';
2489
2490let queueTitle = 'QUEUE_TITLE';
2491currentAVSession.setAVQueueTitle(queueTitle).then(() => {
2492  console.info(`SetAVQueueTitle successfully`);
2493}).catch((err: BusinessError) => {
2494  console.error(`SetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`);
2495});
2496```
2497
2498### setAVQueueTitle<sup>10+</sup>
2499
2500setAVQueueTitle(title: string, callback: AsyncCallback\<void>): void
2501
2502Sets a name for the playlist. This API uses an asynchronous callback to return the result.
2503
2504**System capability**: SystemCapability.Multimedia.AVSession.Core
2505
2506**Parameters**
2507
2508| Name  | Type                                 | Mandatory| Description                                                        |
2509| -------- | --------------------- | ---- | ----------------------------------------------------------- |
2510| title    | string                | Yes  | Name of the playlist.                         |
2511| callback | AsyncCallback\<void>  | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.|
2512
2513**Error codes**
2514
2515For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2516
2517| ID| Error Message|
2518| -------- | ---------------------------------------- |
2519| 6600101  | Session service exception. |
2520| 6600102  | The session does not exist. |
2521
2522**Example**
2523
2524```ts
2525import { BusinessError } from '@ohos.base';
2526
2527let queueTitle = 'QUEUE_TITLE';
2528currentAVSession.setAVQueueTitle(queueTitle, (err: BusinessError) => {
2529  if (err) {
2530    console.error(`SetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`);
2531  } else {
2532    console.info(`SetAVQueueTitle successfully`);
2533  }
2534});
2535```
2536
2537### setExtras<sup>10+</sup>
2538
2539setExtras(extras: {[key: string]: Object}): Promise\<void>
2540
2541Sets a custom media packet in the form of key-value pairs. This API uses a promise to return the result. It is called by the provider.
2542
2543**System capability**: SystemCapability.Multimedia.AVSession.Core
2544
2545**Parameters**
2546
2547| Name | Type                                         | Mandatory| Description                                                       |
2548| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- |
2549| extras | {[key: string]: Object} | Yes  | Key-value pairs of the custom media packet.|
2550
2551> **NOTE**
2552
2553> The **extras** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want (Want)](./js-apis-app-ability-want.md).
2554
2555**Return value**
2556
2557| Type          | Description                         |
2558| -------------- | ----------------------------- |
2559| Promise\<void> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
2560
2561**Error codes**
2562
2563For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2564
2565| ID| Error Message|
2566| -------- | ---------------------------------------- |
2567| 6600101  | Session service exception. |
2568| 6600102  | The session does not exist. |
2569
2570**Example**
2571
2572```ts
2573import avSession from '@ohos.multimedia.avsession';
2574import { BusinessError } from '@ohos.base';
2575
2576let currentAVSession: avSession.AVSession | undefined = undefined;
2577let tag = "createNewSession";
2578let context: Context = getContext(this);
2579
2580avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
2581  if (err) {
2582    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
2583  } else {
2584    currentAVSession = data;
2585  }
2586});
2587if (currentAVSession !== undefined) {
2588  (currentAVSession as avSession.AVSession).setExtras({extras : "This is custom media packet"}).then(() => {
2589    console.info(`setExtras successfully`);
2590  }).catch((err: BusinessError) => {
2591    console.error(`setExtras BusinessError: code: ${err.code}, message: ${err.message}`);
2592  })
2593}
2594```
2595
2596### setExtras<sup>10+</sup>
2597
2598setExtras(extras: {[key: string]: Object}, callback: AsyncCallback\<void>): void
2599
2600Sets a custom media packet in the form of key-value pairs. This API uses an asynchronous callback to return the result. It is called by the provider.
2601
2602**System capability**: SystemCapability.Multimedia.AVSession.Core
2603
2604**Parameters**
2605
2606| Name | Type                                         | Mandatory| Description                                                       |
2607| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- |
2608| extras | {[key: string]: any} | Yes  | Key-value pairs of the custom media packet.|
2609| callback | AsyncCallback\<void>                          | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.|
2610
2611> **NOTE**
2612>
2613> The **extras** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want (Want)](./js-apis-app-ability-want.md).
2614
2615**Error codes**
2616
2617For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2618
2619| ID| Error Message|
2620| -------- | ---------------------------------------- |
2621| 6600101  | Session service exception. |
2622| 6600102  | The session does not exist. |
2623
2624**Example**
2625
2626```ts
2627import avSession from '@ohos.multimedia.avsession';
2628import { BusinessError } from '@ohos.base';
2629
2630let currentAVSession: avSession.AVSession | undefined = undefined;
2631let tag = "createNewSession";
2632let context: Context = getContext(this);
2633
2634avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
2635  if (err) {
2636    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
2637  } else {
2638    currentAVSession = data;
2639  }
2640});
2641if (currentAVSession !== undefined) {
2642  (currentAVSession as avSession.AVSession).setExtras({extras : "This is custom media packet"}, (err: BusinessError) => {
2643    if (err) {
2644      console.error(`setExtras BusinessError: code: ${err.code}, message: ${err.message}`);
2645    }
2646  })
2647}
2648```
2649
2650### getController<sup>10+</sup>
2651
2652getController(): Promise\<AVSessionController>
2653
2654Obtains the controller corresponding to this session. This API uses a promise to return the result.
2655
2656**System capability**: SystemCapability.Multimedia.AVSession.Core
2657
2658**Return value**
2659
2660| Type                                                | Description                         |
2661| ---------------------------------------------------- | ----------------------------- |
2662| Promise<[AVSessionController](#avsessioncontroller10)> | Promise used to return the session controller.|
2663
2664**Error codes**
2665
2666For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2667
2668| ID| Error Message|
2669| -------- | ---------------------------------------- |
2670| 6600101  | Session service exception. |
2671| 6600102  | The session does not exist. |
2672
2673**Example**
2674
2675```ts
2676import { BusinessError } from '@ohos.base';
2677
2678let avsessionController: avSession.AVSessionController;
2679currentAVSession.getController().then((avcontroller: avSession.AVSessionController) => {
2680  avsessionController = avcontroller;
2681  console.info(`GetController : SUCCESS : sessionid : ${avsessionController.sessionId}`);
2682}).catch((err: BusinessError) => {
2683  console.error(`GetController BusinessError: code: ${err.code}, message: ${err.message}`);
2684});
2685```
2686
2687### getController<sup>10+</sup>
2688
2689getController(callback: AsyncCallback\<AVSessionController>): void
2690
2691Obtains the controller corresponding to this session. This API uses an asynchronous callback to return the result.
2692
2693**System capability**: SystemCapability.Multimedia.AVSession.Core
2694
2695**Parameters**
2696
2697| Name  | Type                                                       | Mandatory| Description                      |
2698| -------- | ----------------------------------------------------------- | ---- | -------------------------- |
2699| callback | AsyncCallback<[AVSessionController](#avsessioncontroller10)\> | Yes  | Callback used to return the session controller.|
2700
2701**Error codes**
2702
2703For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2704
2705| ID| Error Message|
2706| -------- | ---------------------------------------- |
2707| 6600101  | Session service exception. |
2708| 6600102  | The session does not exist. |
2709
2710**Example**
2711
2712```ts
2713import { BusinessError } from '@ohos.base';
2714
2715let avsessionController: avSession.AVSessionController;
2716currentAVSession.getController((err: BusinessError, avcontroller: avSession.AVSessionController) => {
2717  if (err) {
2718    console.error(`GetController BusinessError: code: ${err.code}, message: ${err.message}`);
2719  } else {
2720    avsessionController = avcontroller;
2721    console.info(`GetController : SUCCESS : sessionid : ${avsessionController.sessionId}`);
2722  }
2723});
2724```
2725
2726### getAVCastController<sup>10+</sup>
2727
2728getAVCastController(callback: AsyncCallback\<AVCastController>): void
2729
2730Obtains the cast controller when a casting connection is set up. This API uses an asynchronous callback to return the result. If the session is not in the cast state, the controller returns **null**.
2731
2732**System capability**: SystemCapability.Multimedia.AVSession.AVCast
2733
2734**Parameters**
2735
2736| Name   | Type                                                       | Mandatory| Description                                                        |
2737| --------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
2738| callback  | AsyncCallback<[AVCastController](#avcastcontroller10)\> | Yes  | Callback used to return the cast controller.|
2739
2740**Error codes**
2741
2742For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2743
2744| ID| Error Message                                 |
2745| -------- |---------------------------------------|
2746| 6600102  | The session does not exist.           |
2747| 6600110  | The remote connection does not exist. |
2748
2749**Example**
2750
2751```ts
2752import { BusinessError } from '@ohos.base';
2753
2754let aVCastController: avSession.AVCastController;
2755currentAVSession.getAVCastController().then((avcontroller: avSession.AVCastController) => {
2756  aVCastController = avcontroller;
2757  console.info(`getAVCastController : SUCCESS`);
2758}).catch((err: BusinessError) => {
2759  console.error(`getAVCastController BusinessError: code: ${err.code}, message: ${err.message}`);
2760});
2761```
2762
2763### getAVCastController<sup>10+</sup>
2764
2765getAVCastController(): Promise\<AVCastController>
2766
2767Obtains the cast controller when a casting connection is set up. This API uses an asynchronous callback to return the result. If the session is not in the cast state, the controller returns **null**.
2768
2769**System capability**: SystemCapability.Multimedia.AVSession.AVCast
2770
2771**Return value**
2772
2773| Type                                                       | Description                                                        |
2774| --------- | ------------------------------------------------------------ |
2775| Promise<[AVCastController](#avcastcontroller10)\>  | Promise used to return the cast controller.|
2776
2777**Error codes**
2778
2779For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2780
2781| ID| Error Message|
2782| -------- | --------------------------------------- |
2783| 6600102  | The session does not exist. |
2784| 6600110  | The remote connection does not exist. |
2785
2786**Example**
2787
2788```ts
2789import { BusinessError } from '@ohos.base';
2790
2791let aVCastController: avSession.AVCastController;
2792currentAVSession.getAVCastController((err: BusinessError, avcontroller: avSession.AVCastController) => {
2793  if (err) {
2794    console.error(`getAVCastController BusinessError: code: ${err.code}, message: ${err.message}`);
2795  } else {
2796    aVCastController = avcontroller;
2797    console.info(`getAVCastController : SUCCESS`);
2798  }
2799});
2800```
2801
2802### getOutputDevice<sup>10+</sup>
2803
2804getOutputDevice(): Promise\<OutputDeviceInfo>
2805
2806Obtains information about the output device for this session. This API uses a promise to return the result.
2807
2808**System capability**: SystemCapability.Multimedia.AVSession.Core
2809
2810**Return value**
2811
2812| Type                                          | Description                             |
2813| ---------------------------------------------- | --------------------------------- |
2814| Promise<[OutputDeviceInfo](#outputdeviceinfo10)> | Promise used to return the output device information.|
2815
2816**Error codes**
2817
2818For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2819
2820| ID| Error Message|
2821| -------- | ---------------------------------------- |
2822| 6600101  | Session service exception. |
2823| 6600102  | The session does not exist. |
2824
2825**Example**
2826
2827```ts
2828import { BusinessError } from '@ohos.base';
2829
2830currentAVSession.getOutputDevice().then((outputDeviceInfo: avSession.OutputDeviceInfo) => {
2831  console.info(`GetOutputDevice : SUCCESS : devices length : ${outputDeviceInfo.devices.length}`);
2832}).catch((err: BusinessError) => {
2833  console.error(`GetOutputDevice BusinessError: code: ${err.code}, message: ${err.message}`);
2834})
2835```
2836
2837### getOutputDevice<sup>10+</sup>
2838
2839getOutputDevice(callback: AsyncCallback\<OutputDeviceInfo>): void
2840
2841Obtains information about the output device for this session. This API uses an asynchronous callback to return the result.
2842
2843**System capability**: SystemCapability.Multimedia.AVSession.Core
2844
2845**Parameters**
2846
2847| Name  | Type                                                 | Mandatory| Description                          |
2848| -------- | ----------------------------------------------------- | ---- | ------------------------------ |
2849| callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo10)\> | Yes  | Callback used to return the information obtained.|
2850
2851**Error codes**
2852
2853For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2854
2855| ID| Error Message|
2856| -------- | ---------------------------------------- |
2857| 6600101  | Session service exception. |
2858| 6600102  | The session does not exist. |
2859
2860**Example**
2861
2862```ts
2863import { BusinessError } from '@ohos.base';
2864
2865currentAVSession.getOutputDevice((err: BusinessError, outputDeviceInfo: avSession.OutputDeviceInfo) => {
2866  if (err) {
2867    console.error(`GetOutputDevice BusinessError: code: ${err.code}, message: ${err.message}`);
2868  } else {
2869    console.info(`GetOutputDevice : SUCCESS : devices length : ${outputDeviceInfo.devices.length}`);
2870  }
2871});
2872```
2873
2874### activate<sup>10+</sup>
2875
2876activate(): Promise\<void>
2877
2878Activates this session. A session can be used only after being activated. This API uses a promise to return the result.
2879
2880**System capability**: SystemCapability.Multimedia.AVSession.Core
2881
2882**Return value**
2883
2884| Type          | Description                         |
2885| -------------- | ----------------------------- |
2886| Promise\<void> | Promise used to return the result. If the session is activated, no value is returned; otherwise, an error object is returned.|
2887
2888**Error codes**
2889
2890For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2891
2892| ID| Error Message|
2893| -------- | ---------------------------------------- |
2894| 6600101  | Session service exception. |
2895| 6600102  | The session does not exist. |
2896
2897**Example**
2898
2899```ts
2900import { BusinessError } from '@ohos.base';
2901
2902currentAVSession.activate().then(() => {
2903  console.info(`Activate : SUCCESS `);
2904}).catch((err: BusinessError) => {
2905  console.error(`Activate BusinessError: code: ${err.code}, message: ${err.message}`);
2906});
2907```
2908
2909### activate<sup>10+</sup>
2910
2911activate(callback: AsyncCallback\<void>): void
2912
2913Activates this session. A session can be used only after being activated. This API uses an asynchronous callback to return the result.
2914
2915**System capability**: SystemCapability.Multimedia.AVSession.Core
2916
2917**Parameters**
2918
2919| Name  | Type                | Mandatory| Description      |
2920| -------- | -------------------- | ---- | ---------- |
2921| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the session is activated, **err** is **undefined**; otherwise, **err** is an error object.|
2922
2923**Error codes**
2924
2925For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2926
2927| ID| Error Message|
2928| -------- | ---------------------------------------- |
2929| 6600101  | Session service exception. |
2930| 6600102  | The session does not exist. |
2931
2932**Example**
2933
2934```ts
2935import { BusinessError } from '@ohos.base';
2936
2937currentAVSession.activate((err: BusinessError) => {
2938  if (err) {
2939    console.error(`Activate BusinessError: code: ${err.code}, message: ${err.message}`);
2940  } else {
2941    console.info(`Activate : SUCCESS `);
2942  }
2943});
2944```
2945
2946### deactivate<sup>10+</sup>
2947
2948deactivate(): Promise\<void>
2949
2950Deactivates this session. You can use [activate](#activate10) to activate the session again. This API uses a promise to return the result.
2951
2952**System capability**: SystemCapability.Multimedia.AVSession.Core
2953
2954**Return value**
2955
2956| Type          | Description                         |
2957| -------------- | ----------------------------- |
2958| Promise\<void> | Promise used to return the result. If the session is deactivated, no value is returned; otherwise, an error object is returned.|
2959
2960**Error codes**
2961
2962For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
2963
2964| ID| Error Message|
2965| -------- | ---------------------------------------- |
2966| 6600101  | Session service exception. |
2967| 6600102  | The session does not exist. |
2968
2969**Example**
2970
2971```ts
2972import { BusinessError } from '@ohos.base';
2973
2974currentAVSession.deactivate().then(() => {
2975  console.info(`Deactivate : SUCCESS `);
2976}).catch((err: BusinessError) => {
2977  console.error(`Deactivate BusinessError: code: ${err.code}, message: ${err.message}`);
2978});
2979```
2980
2981### deactivate<sup>10+</sup>
2982
2983deactivate(callback: AsyncCallback\<void>): void
2984
2985Deactivates this session. This API uses an asynchronous callback to return the result.
2986
2987Deactivates this session. You can use [activate](#activate10) to activate the session again.
2988
2989**System capability**: SystemCapability.Multimedia.AVSession.Core
2990
2991**Parameters**
2992
2993| Name  | Type                | Mandatory| Description      |
2994| -------- | -------------------- | ---- | ---------- |
2995| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the session is deactivated, **err** is **undefined**; otherwise, **err** is an error object.|
2996
2997**Error codes**
2998
2999For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3000
3001| ID| Error Message|
3002| -------- | ---------------------------------------- |
3003| 6600101  | Session service exception. |
3004| 6600102  | The session does not exist. |
3005
3006**Example**
3007
3008```ts
3009import { BusinessError } from '@ohos.base';
3010
3011currentAVSession.deactivate((err: BusinessError) => {
3012  if (err) {
3013    console.error(`Deactivate BusinessError: code: ${err.code}, message: ${err.message}`);
3014  } else {
3015    console.info(`Deactivate : SUCCESS `);
3016  }
3017});
3018```
3019
3020### destroy<sup>10+</sup>
3021
3022destroy(): Promise\<void>
3023
3024Destroys this session. This API uses a promise to return the result.
3025
3026**System capability**: SystemCapability.Multimedia.AVSession.Core
3027
3028**Return value**
3029
3030| Type          | Description                         |
3031| -------------- | ----------------------------- |
3032| Promise\<void> | Promise used to return the result. If the session is destroyed, no value is returned; otherwise, an error object is returned.|
3033
3034**Error codes**
3035
3036For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3037
3038| ID| Error Message|
3039| -------- | ---------------------------------------- |
3040| 6600101  | Session service exception. |
3041| 6600102  | The session does not exist. |
3042
3043**Example**
3044
3045```ts
3046import { BusinessError } from '@ohos.base';
3047
3048currentAVSession.destroy().then(() => {
3049  console.info(`Destroy : SUCCESS `);
3050}).catch((err: BusinessError) => {
3051  console.error(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`);
3052});
3053```
3054
3055### destroy<sup>10+</sup>
3056
3057destroy(callback: AsyncCallback\<void>): void
3058
3059Destroys this session. This API uses an asynchronous callback to return the result.
3060
3061**System capability**: SystemCapability.Multimedia.AVSession.Core
3062
3063**Parameters**
3064
3065| Name  | Type                | Mandatory| Description      |
3066| -------- | -------------------- | ---- | ---------- |
3067| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the session is destroyed, **err** is **undefined**; otherwise, **err** is an error object.|
3068
3069**Error codes**
3070
3071For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3072
3073| ID| Error Message|
3074| -------- | ---------------------------------------- |
3075| 6600101  | Session service exception. |
3076| 6600102  | The session does not exist. |
3077
3078**Example**
3079
3080```ts
3081import { BusinessError } from '@ohos.base';
3082
3083currentAVSession.destroy((err: BusinessError) => {
3084  if (err) {
3085    console.error(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`);
3086  } else {
3087    console.info(`Destroy : SUCCESS `);
3088  }
3089});
3090```
3091
3092### on('play')<sup>10+</sup>
3093
3094on(type: 'play', callback: () => void): void
3095
3096Subscribes to play command events. The subscription means that the application supports the play command.
3097
3098Only one callback can be registered for each playback command. If a new callback is registered, the previous callback is replaced.
3099
3100**System capability**: SystemCapability.Multimedia.AVSession.Core
3101
3102**Parameters**
3103
3104| Name  | Type                | Mandatory| Description                                                        |
3105| -------- | -------------------- | ---- | ------------------------------------------------------------ |
3106| type     | string               | Yes  | Event type. The event **'play'** is triggered when the command for starting playback is sent to the session.|
3107| callback | () => void | Yes  | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object.                                       |
3108
3109**Error codes**
3110
3111For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3112
3113| ID| Error Message|
3114| -------- | ---------------------------------------- |
3115| 6600101  | Session service exception. |
3116| 6600102  | The session does not exist. |
3117
3118**Example**
3119
3120```ts
3121currentAVSession.on('play', () => {
3122  console.info(`on play entry`);
3123});
3124```
3125
3126### on('pause')<sup>10+</sup>
3127
3128on(type: 'pause', callback: () => void): void
3129
3130Subscribes to pause command events. The subscription means that the application supports the pause command.
3131
3132Only one callback can be registered for each playback command. If a new callback is registered, the previous callback is replaced.
3133
3134**System capability**: SystemCapability.Multimedia.AVSession.Core
3135
3136**Parameters**
3137
3138| Name  | Type                | Mandatory| Description                                                        |
3139| -------- | -------------------- | ---- | ------------------------------------------------------------ |
3140| type     | string               | Yes  | Event type. The event **'pause'** is triggered when the command for pausing the playback is sent to the session.|
3141| callback | () => void | Yes  | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object.    |
3142
3143**Error codes**
3144
3145For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3146
3147| ID| Error Message|
3148| -------- | ---------------------------------------- |
3149| 6600101  | Session service exception. |
3150| 6600102  | The session does not exist. |
3151
3152**Example**
3153
3154```ts
3155currentAVSession.on('pause', () => {
3156  console.info(`on pause entry`);
3157});
3158```
3159
3160### on('stop')<sup>10+</sup>
3161
3162on(type:'stop', callback: () => void): void
3163
3164Subscribes to stop command events. The subscription means that the application supports the stop command.
3165
3166Only one callback can be registered for each playback command. If a new callback is registered, the previous callback is replaced.
3167
3168**System capability**: SystemCapability.Multimedia.AVSession.Core
3169
3170**Parameters**
3171
3172| Name  | Type                | Mandatory| Description                                                        |
3173| -------- | -------------------- | ---- | ------------------------------------------------------------ |
3174| type     | string               | Yes  | Event type. The event **'stop'** is triggered when the command for stopping the playback is sent to the session.|
3175| callback | () => void | Yes  | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object.         |
3176
3177**Error codes**
3178
3179For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3180
3181| ID| Error Message|
3182| -------- | ---------------------------------------- |
3183| 6600101  | Session service exception. |
3184| 6600102  | The session does not exist. |
3185
3186**Example**
3187
3188```ts
3189currentAVSession.on('stop', () => {
3190  console.info(`on stop entry`);
3191});
3192```
3193
3194### on('playNext')<sup>10+</sup>
3195
3196on(type:'playNext', callback: () => void): void
3197
3198Subscribes to playNext command events. The subscription means that the application supports the playNext command.
3199
3200Only one callback can be registered for each playback command. If a new callback is registered, the previous callback is replaced.
3201
3202**System capability**: SystemCapability.Multimedia.AVSession.Core
3203
3204**Parameters**
3205
3206| Name  | Type                | Mandatory| Description                                                        |
3207| -------- | -------------------- | ---- | ------------------------------------------------------------ |
3208| type     | string               | Yes  | Event type. The event **'playNext'** is triggered when the command for playing the next item is sent to the session.|
3209| callback | () => void | Yes  | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object.    |
3210
3211**Error codes**
3212
3213For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3214
3215| ID| Error Message|
3216| -------- | ---------------------------------------- |
3217| 6600101  | Session service exception. |
3218| 6600102  | The session does not exist. |
3219
3220**Example**
3221
3222```ts
3223currentAVSession.on('playNext', () => {
3224  console.info(`on playNext entry`);
3225});
3226```
3227
3228### on('playPrevious')<sup>10+</sup>
3229
3230on(type:'playPrevious', callback: () => void): void
3231
3232Subscribes to playPrevious command events. The subscription means that the application supports the playPrevious command.
3233
3234Only one callback can be registered for each playback command. If a new callback is registered, the previous callback is replaced.
3235
3236**System capability**: SystemCapability.Multimedia.AVSession.Core
3237
3238**Parameters**
3239
3240| Name  | Type                | Mandatory| Description                                                        |
3241| -------- | -------------------- | ---- | ------------------------------------------------------------ |
3242| type     | string               | Yes  | Event type. The event **'playPrevious'** is triggered when the command for playing the previous item sent to the session.|
3243| callback | () => void | Yes  | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object.      |
3244
3245**Error codes**
3246
3247For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3248
3249| ID| Error Message|
3250| -------- | ---------------------------------------- |
3251| 6600101  | Session service exception. |
3252| 6600102  | The session does not exist. |
3253
3254**Example**
3255
3256```ts
3257currentAVSession.on('playPrevious', () => {
3258  console.info(`on playPrevious entry`);
3259});
3260```
3261
3262### on('fastForward')<sup>10+</sup>
3263
3264on(type: 'fastForward', callback: (time?: number) => void): void
3265
3266Subscribes to fastForward command events. The subscription means that the application supports the fastForward command.
3267
3268Only one callback can be registered for each playback command. If a new callback is registered, the previous callback is replaced.
3269
3270**System capability**: SystemCapability.Multimedia.AVSession.Core
3271
3272**Parameters**
3273
3274| Name  | Type                | Mandatory| Description                                                        |
3275| -------- | -------------------- | ---- | ------------------------------------------------------------ |
3276| type     | string               | Yes  | Event type. The event **'fastForward'** is triggered when the command for fast forwarding is sent to the session.|
3277| callback | (time?: number) => void | Yes  | Callback used for subscription. The **time** parameter in the callback indicates the time to seek to, in seconds.   |
3278
3279**Error codes**
3280
3281For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3282
3283| ID| Error Message|
3284| -------- | ---------------------------------------- |
3285| 6600101  | Session service exception. |
3286| 6600102  | The session does not exist. |
3287
3288**Example**
3289
3290```ts
3291currentAVSession.on('fastForward', (time?: number) => {
3292  console.info(`on fastForward entry`);
3293});
3294```
3295
3296### on('rewind')<sup>10+</sup>
3297
3298on(type:'rewind', callback: (time?: number) => void): void
3299
3300Subscribes to rewind command events.
3301
3302After the callback is canceled, the list of supported commands must be updated.
3303
3304**System capability**: SystemCapability.Multimedia.AVSession.Core
3305
3306**Parameters**
3307
3308| Name  | Type                | Mandatory| Description                                                        |
3309| -------- | -------------------- | ---- | ------------------------------------------------------------ |
3310| type     | string               | Yes  | Event type. The event **'rewind'** is triggered when the command for rewinding is sent to the session.|
3311| callback | (time?: number) => void | Yes  | Callback used for subscription. The **time** parameter in the callback indicates the time to seek to, in seconds.     |
3312
3313**Error codes**
3314
3315For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3316
3317| ID| Error Message|
3318| -------- | ---------------------------------------- |
3319| 6600101  | Session service exception. |
3320| 6600102  | The session does not exist. |
3321
3322**Example**
3323
3324```ts
3325currentAVSession.on('rewind', (time?: number) => {
3326  console.info(`on rewind entry`);
3327});
3328```
3329
3330### on('seek')<sup>10+</sup>
3331
3332on(type: 'seek', callback: (time: number) => void): void
3333
3334Subscribes to seek command events.
3335
3336**System capability**: SystemCapability.Multimedia.AVSession.Core
3337
3338**Parameters**
3339
3340| Name  | Type                  | Mandatory| Description                                                        |
3341| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
3342| type     | string                 | Yes  | Event type. The event **'seek'** is triggered when the seek command is sent to the session.|
3343| callback | (time: number) => void | Yes  | Callback used for subscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds.                  |
3344
3345**Error codes**
3346
3347For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3348
3349| ID| Error Message|
3350| -------- | ---------------------------------------- |
3351| 6600101  | Session service exception. |
3352| 6600102  | The session does not exist. |
3353
3354**Example**
3355
3356```ts
3357currentAVSession.on('seek', (time: number) => {
3358  console.info(`on seek entry time : ${time}`);
3359});
3360```
3361
3362### on('setSpeed')<sup>10+</sup>
3363
3364on(type: 'setSpeed', callback: (speed: number) => void): void
3365
3366Subscribes to setSpeed command events.
3367
3368**System capability**: SystemCapability.Multimedia.AVSession.Core
3369
3370**Parameters**
3371
3372| Name  | Type                   | Mandatory| Description                                                        |
3373| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
3374| type     | string                  | Yes  | Event type. The event **'setSpeed'** is triggered when the command for setting the playback speed is sent to the session.|
3375| callback | (speed: number) => void | Yes  | Callback used for subscription. The **speed** parameter in the callback indicates the playback speed.                             |
3376
3377**Error codes**
3378
3379For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3380
3381| ID| Error Message|
3382| -------- | ---------------------------------------- |
3383| 6600101  | Session service exception. |
3384| 6600102  | The session does not exist. |
3385
3386**Example**
3387
3388```ts
3389currentAVSession.on('setSpeed', (speed: number) => {
3390  console.info(`on setSpeed speed : ${speed}`);
3391});
3392```
3393
3394### on('setLoopMode')<sup>10+</sup>
3395
3396on(type: 'setLoopMode', callback: (mode: LoopMode) => void): void
3397
3398Subscribes to setLoopMode command events.
3399
3400**System capability**: SystemCapability.Multimedia.AVSession.Core
3401
3402**Parameters**
3403
3404| Name   | Type                                  | Mandatory| Description |
3405| -------- | ------------------------------------- | ---- | ---- |
3406| type     | string                                | Yes  | Event type. The event **'setLoopMode'** is triggered when the command for setting the loop mode is sent to the session.|
3407| callback | (mode: [LoopMode](#loopmode10)) => void | Yes  | Callback used for subscription. The **mode** parameter in the callback indicates the loop mode.                              |
3408
3409**Error codes**
3410
3411For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3412
3413| ID| Error Message|
3414| -------- | ---------------------------------------- |
3415| 6600101  | Session service exception. |
3416| 6600102  | The session does not exist. |
3417
3418**Example**
3419
3420```ts
3421currentAVSession.on('setLoopMode', (mode: avSession.LoopMode) => {
3422  console.info(`on setLoopMode mode : ${mode}`);
3423});
3424```
3425
3426### on('toggleFavorite')<sup>10+</sup>
3427
3428on(type: 'toggleFavorite', callback: (assetId: string) => void): void
3429
3430Subscribes to toggleFavorite command events.
3431
3432**System capability**: SystemCapability.Multimedia.AVSession.Core
3433
3434**Parameters**
3435
3436| Name  | Type                     | Mandatory| Description                                                        |
3437| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
3438| type     | string                    | Yes  | Event type. The event **'toggleFavorite'** is triggered when the command for favoriting the media asset is sent to the session.|
3439| callback | (assetId: string) => void | Yes  | Callback used for subscription. The **assetId** parameter in the callback indicates the media asset ID.                             |
3440
3441**Error codes**
3442
3443For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3444
3445| ID| Error Message|
3446| -------- | ---------------------------------------- |
3447| 6600101  | Session service exception. |
3448| 6600102  | The session does not exist. |
3449
3450**Example**
3451
3452```ts
3453currentAVSession.on('toggleFavorite', (assetId: string) => {
3454  console.info(`on toggleFavorite mode : ${assetId}`);
3455});
3456```
3457
3458### on('skipToQueueItem')<sup>10+</sup>
3459
3460on(type: 'skipToQueueItem', callback: (itemId: number) => void): void
3461
3462Subscribes to the event that indicates an item in the playlist is selected. The session can play the selected item.
3463
3464**System capability**: SystemCapability.Multimedia.AVSession.Core
3465
3466**Parameters**
3467
3468| Name  | Type                     | Mandatory| Description                                                                                     |
3469| -------- | ------------------------ | ---- | ---------------------------------------------------------------------------------------- |
3470| type     | string                   | Yes  | Event type. The event **'skipToQueueItem'** is triggered when an item in the playlist is selected.|
3471| callback | (itemId: number) => void | Yes  | Callback used for subscription. The **itemId** parameter in the callback indicates the ID of the selected item.                                               |
3472
3473**Error codes**
3474
3475For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3476
3477| ID| Error Message|
3478| -------- | ---------------------------------------- |
3479| 6600101  | Session service exception. |
3480| 6600102  | The session does not exist. |
3481
3482**Example**
3483
3484```ts
3485currentAVSession.on('skipToQueueItem', (itemId: number) => {
3486  console.info(`on skipToQueueItem id : ${itemId}`);
3487});
3488```
3489
3490### on('handleKeyEvent')<sup>10+</sup>
3491
3492on(type: 'handleKeyEvent', callback: (event: KeyEvent) => void): void
3493
3494Subscribes to key events.
3495
3496**System capability**: SystemCapability.Multimedia.AVSession.Core
3497
3498**Parameters**
3499
3500| Name  | Type                                                        | Mandatory| Description                                                        |
3501| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3502| type     | string                                                       | Yes  | Event type. The event **'handleKeyEvent'** is triggered when a key event is sent to the session.|
3503| callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | Yes  | Callback used for subscription. The **event** parameter in the callback indicates the key event.                             |
3504
3505**Error codes**
3506
3507For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3508
3509| ID| Error Message|
3510| -------- | ---------------------------------------- |
3511| 6600101  | Session service exception. |
3512| 6600102  | The session does not exist. |
3513
3514**Example**
3515
3516```ts
3517import keyEvent from '@ohos.multimodalInput.keyEvent';
3518
3519currentAVSession.on('handleKeyEvent', (event: keyEvent.KeyEvent) => {
3520  console.info(`on handleKeyEvent event : ${event}`);
3521});
3522
3523```
3524
3525### on('outputDeviceChange')<sup>10+</sup>
3526
3527on(type: 'outputDeviceChange', callback: (state: ConnectionState, device: OutputDeviceInfo) => void): void
3528
3529Subscribes to output device change events.
3530
3531**System capability**: SystemCapability.Multimedia.AVSession.Core
3532
3533**Parameters**
3534
3535| Name  | Type                                                   | Mandatory| Description                                                        |
3536| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ |
3537| type     | string                                                  | Yes  | Event type. The event **'outputDeviceChange'** is triggered when the output device changes.|
3538| callback | (state: [ConnectionState](#connectionstate10), device: [OutputDeviceInfo](#outputdeviceinfo10)) => void | Yes  | Callback used for subscription. The **device** parameter in the callback indicates the output device information.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                        |
3539
3540**Error codes**
3541
3542For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3543
3544| ID| Error Message|
3545| -------- | ---------------------------------------- |
3546| 6600101  | Session service exception. |
3547| 6600102  | The session does not exist. |
3548
3549**Example**
3550
3551```ts
3552currentAVSession.on('outputDeviceChange', (state: avSession.ConnectionState, device: avSession.OutputDeviceInfo) => {
3553  console.info(`on outputDeviceChange device : ${device}`);
3554});
3555```
3556
3557### on('commonCommand')<sup>10+</sup>
3558
3559on(type: 'commonCommand', callback: (command: string, args: {[key: string]: Object}) => void): void
3560
3561Subscribes to custom control command change events.
3562
3563**System capability**: SystemCapability.Multimedia.AVSession.Core
3564
3565**Parameters**
3566
3567| Name  | Type                                                        | Mandatory| Description                                                        |
3568| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3569| type     | string                                                       | Yes  | Event type. The event **'commonCommand'** is triggered when a custom control command changes.|
3570| callback | (command: string, args: {[key:string]: Object}) => void         | Yes  | Callback used for subscription. The **command** parameter in the callback indicates the name of the changed custom control command, and **args** indicates the parameters carried in the command. The parameters must be the same as those set in [sendCommonCommand](#sendcommoncommand10).         |
3571
3572**Error codes**
3573
3574For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3575
3576| ID| Error Message|
3577| -------- | ------------------------------ |
3578| 6600101  | Session service exception. |
3579| 6600102  | The session does not exist. |
3580
3581**Example**
3582
3583```ts
3584import { BusinessError } from '@ohos.base';
3585import avSession from '@ohos.multimedia.avsession';
3586let currentAVSession: avSession.AVSession | undefined = undefined;
3587let tag = "createNewSession";
3588let context: Context = getContext(this);
3589
3590avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
3591  if (err) {
3592    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
3593  } else {
3594    currentAVSession = data;
3595  }
3596});
3597if (currentAVSession !== undefined) {
3598  (currentAVSession as avSession.AVSession).on('commonCommand', (commonCommand, args) => {
3599    console.info(`OnCommonCommand, the command is ${commonCommand}, args: ${JSON.stringify(args)}`);
3600  });
3601}
3602```
3603
3604### off('play')<sup>10+</sup>
3605
3606off(type: 'play', callback?: () => void): void
3607
3608Unsubscribes from play command events.
3609
3610After the callback is canceled, the list of supported commands must be updated.
3611
3612**System capability**: SystemCapability.Multimedia.AVSession.Core
3613
3614**Parameters**
3615
3616| Name   | Type                 | Mandatory| Description                                                                                                                        |
3617| -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- |
3618| type     | string               | Yes  | Event type, which is **'play'** in this case.|
3619| callback | () => void | No  | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                           |
3620
3621**Error codes**
3622
3623For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3624
3625| ID| Error Message|
3626| -------- | ---------------------------------------- |
3627| 6600101  | Session service exception. |
3628| 6600102  | The session does not exist. |
3629
3630**Example**
3631
3632```ts
3633currentAVSession.off('play');
3634```
3635
3636### off('pause')<sup>10+</sup>
3637
3638off(type: 'pause', callback?: () => void): void
3639
3640Unsubscribes from pause command events.
3641
3642After the callback is canceled, the list of supported commands must be updated.
3643
3644**System capability**: SystemCapability.Multimedia.AVSession.Core
3645
3646**Parameters**
3647
3648| Name   | Type                 | Mandatory| Description                                                                                                                        |
3649| -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- |
3650| type     | string               | Yes  | Event type, which is **'pause'** in this case.|
3651| callback | () => void | No  | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.|
3652
3653**Error codes**
3654
3655For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3656
3657| ID| Error Message|
3658| -------- | ---------------------------------------- |
3659| 6600101  | Session service exception. |
3660| 6600102  | The session does not exist. |
3661
3662**Example**
3663
3664```ts
3665currentAVSession.off('pause');
3666```
3667
3668### off('stop')<sup>10+</sup>
3669
3670off(type: 'stop', callback?: () => void): void
3671
3672Unsubscribes from stop command events.
3673
3674After the callback is canceled, the list of supported commands must be updated.
3675
3676**System capability**: SystemCapability.Multimedia.AVSession.Core
3677
3678**Parameters**
3679
3680| Name   | Type                 | Mandatory| Description                                                                                                                        |
3681| -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- |
3682| type     | string               | Yes  | Event type, which is **'stop'** in this case.|
3683| callback | () => void | No  | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                           |
3684
3685**Error codes**
3686
3687For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3688
3689| ID| Error Message|
3690| -------- | ---------------------------------------- |
3691| 6600101  | Session service exception. |
3692| 6600102  | The session does not exist. |
3693
3694**Example**
3695
3696```ts
3697currentAVSession.off('stop');
3698```
3699
3700### off('playNext')<sup>10+</sup>
3701
3702off(type: 'playNext', callback?: () => void): void
3703
3704Unsubscribes from playNext command events.
3705
3706After the callback is canceled, the list of supported commands must be updated.
3707
3708**System capability**: SystemCapability.Multimedia.AVSession.Core
3709
3710**Parameters**
3711
3712| Name   | Type                 | Mandatory| Description                                                                                                                        |
3713| -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- |
3714| type     | string               | Yes  | Event type, which is **'playNext'** in this case.|
3715| callback | () => void | No  | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                           |
3716
3717**Error codes**
3718
3719For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3720
3721| ID| Error Message|
3722| -------- | ---------------------------------------- |
3723| 6600101  | Session service exception. |
3724| 6600102  | The session does not exist. |
3725
3726**Example**
3727
3728```ts
3729currentAVSession.off('playNext');
3730```
3731
3732### off('playPrevious')<sup>10+</sup>
3733
3734off(type: 'playPrevious', callback?: () => void): void
3735
3736Unsubscribes from playPrevious command events.
3737
3738After the callback is canceled, the list of supported commands must be updated.
3739
3740**System capability**: SystemCapability.Multimedia.AVSession.Core
3741
3742**Parameters**
3743
3744| Name   | Type                 | Mandatory| Description                                                                                                                        |
3745| -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- |
3746| type     | string               | Yes  | Event type, which is **'playPrevious'** in this case.|
3747| callback | () => void | No  | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                           |
3748
3749**Error codes**
3750
3751For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3752
3753| ID| Error Message|
3754| -------- | ---------------------------------------- |
3755| 6600101  | Session service exception. |
3756| 6600102  | The session does not exist. |
3757
3758**Example**
3759
3760```ts
3761currentAVSession.off('playPrevious');
3762```
3763
3764### off('fastForward')<sup>10+</sup>
3765
3766off(type: 'fastForward', callback?: () => void): void
3767
3768Unsubscribes from fastForward command events.
3769
3770After the callback is canceled, the list of supported commands must be updated.
3771
3772**System capability**: SystemCapability.Multimedia.AVSession.Core
3773
3774**Parameters**
3775
3776| Name   | Type                 | Mandatory| Description                                                                                                                        |
3777| -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- |
3778| type     | string               | Yes  | Event type, which is **'fastForward'** in this case.|
3779| callback | () => void | No  | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                           |
3780
3781**Error codes**
3782
3783For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3784
3785| ID| Error Message|
3786| -------- | ---------------------------------------- |
3787| 6600101  | Session service exception. |
3788| 6600102  | The session does not exist. |
3789
3790**Example**
3791
3792```ts
3793currentAVSession.off('fastForward');
3794```
3795
3796### off('rewind')<sup>10+</sup>
3797
3798off(type: 'rewind', callback?: () => void): void
3799
3800Unsubscribes from rewind command events.
3801
3802**System capability**: SystemCapability.Multimedia.AVSession.Core
3803
3804**Parameters**
3805
3806| Name   | Type                 | Mandatory| Description                                                                                                                        |
3807| -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- |
3808| type     | string               | Yes  | Event type, which is **'rewind'** in this case.|
3809| callback | () => void | No  | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                           |
3810
3811**Error codes**
3812
3813For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3814
3815| ID| Error Message|
3816| -------- | ---------------------------------------- |
3817| 6600101  | Session service exception. |
3818| 6600102  | The session does not exist. |
3819
3820**Example**
3821
3822```ts
3823currentAVSession.off('rewind');
3824```
3825
3826### off('seek')<sup>10+</sup>
3827
3828off(type: 'seek', callback?: (time: number) => void): void
3829
3830Unsubscribes from seek command events.
3831
3832**System capability**: SystemCapability.Multimedia.AVSession.Core
3833
3834**Parameters**
3835
3836| Name  | Type                  | Mandatory| Description                                         |
3837| -------- | ---------------------- | ---- | ----------------------------------------- |
3838| type     | string                 | Yes  | Event type, which is **'seek'** in this case.      |
3839| callback | (time: number) => void | No  | Callback used for unsubscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.       |
3840
3841**Error codes**
3842
3843For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3844
3845| ID| Error Message|
3846| -------- | ---------------------------------------- |
3847| 6600101  | Session service exception. |
3848| 6600102  | The session does not exist. |
3849
3850**Example**
3851
3852```ts
3853currentAVSession.off('seek');
3854```
3855
3856### off('setSpeed')<sup>10+</sup>
3857
3858off(type: 'setSpeed', callback?: (speed: number) => void): void
3859
3860Unsubscribes from setSpeed command events.
3861
3862**System capability**: SystemCapability.Multimedia.AVSession.Core
3863
3864**Parameters**
3865
3866| Name  | Type                   | Mandatory| Description                                          |
3867| -------- | ----------------------- | ---- | -------------------------------------------|
3868| type     | string                  | Yes  | Event type, which is **'setSpeed'** in this case.   |
3869| callback | (speed: number) => void | No  | Callback used for unsubscription. The **speed** parameter in the callback indicates the playback speed.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                |
3870
3871**Error codes**
3872
3873For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3874
3875| ID| Error Message|
3876| -------- | ---------------------------------------- |
3877| 6600101  | Session service exception. |
3878| 6600102  | The session does not exist. |
3879
3880**Example**
3881
3882```ts
3883currentAVSession.off('setSpeed');
3884```
3885
3886### off('setLoopMode')<sup>10+</sup>
3887
3888off(type: 'setLoopMode', callback?: (mode: LoopMode) => void): void
3889
3890Unsubscribes from setSpeed command events.
3891
3892**System capability**: SystemCapability.Multimedia.AVSession.Core
3893
3894**Parameters**
3895
3896| Name  | Type                                 | Mandatory| Description    |
3897| -------- | ------------------------------------- | ---- | ----- |
3898| type     | string | Yes  | Event type, which is **'setLoopMode'** in this case.|
3899| callback | (mode: [LoopMode](#loopmode10)) => void | No  | Callback used for unsubscription. The **mode** parameter in the callback indicates the loop mode.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.|
3900
3901**Error codes**
3902
3903For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3904
3905| ID| Error Message|
3906| -------- | ---------------------------------------- |
3907| 6600101  | Session service exception. |
3908| 6600102  | The session does not exist. |
3909
3910**Example**
3911
3912```ts
3913currentAVSession.off('setLoopMode');
3914```
3915
3916### off('toggleFavorite')<sup>10+</sup>
3917
3918off(type: 'toggleFavorite', callback?: (assetId: string) => void): void
3919
3920Unsubscribes from toggleFavorite command events.
3921
3922**System capability**: SystemCapability.Multimedia.AVSession.Core
3923
3924**Parameters**
3925
3926| Name  | Type                     | Mandatory| Description                                                        |
3927| -------- | ------------------------- | ---- | -------------------------------------------------------- |
3928| type     | string                    | Yes  | Event type, which is **'toggleFavorite'** in this case.           |
3929| callback | (assetId: string) => void | No  | Callback used for unsubscription. The **assetId** parameter in the callback indicates the media asset ID.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                              |
3930
3931**Error codes**
3932
3933For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3934
3935| ID| Error Message|
3936| -------- | ---------------------------------------- |
3937| 6600101  | Session service exception. |
3938| 6600102  | The session does not exist. |
3939
3940**Example**
3941
3942```ts
3943currentAVSession.off('toggleFavorite');
3944```
3945
3946### off('skipToQueueItem')<sup>10+</sup>
3947
3948off(type: 'skipToQueueItem', callback?: (itemId: number) => void): void
3949
3950Unsubscribes from the event that indicates an item in the playlist is selected.
3951
3952**System capability**: SystemCapability.Multimedia.AVSession.Core
3953
3954**Parameters**
3955
3956| Name  | Type                     | Mandatory| Description                                                                                                                                                       |
3957| -------- | ------------------------ | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
3958| type     | string                   | Yes  | Event type, which is **'skipToQueueItem'** in this case.                                                                                                         |
3959| callback | (itemId: number) => void | No  | Callback used for unsubscription. The **itemId** parameter in the callback indicates the ID of the item.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.|
3960
3961**Error codes**
3962
3963For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3964
3965| ID| Error Message|
3966| -------- | ---------------------------------------- |
3967| 6600101  | Session service exception. |
3968| 6600102  | The session does not exist. |
3969
3970**Example**
3971
3972```ts
3973currentAVSession.off('skipToQueueItem');
3974```
3975
3976### off('handleKeyEvent')<sup>10+</sup>
3977
3978off(type: 'handleKeyEvent', callback?: (event: KeyEvent) => void): void
3979
3980Unsubscribes from key events.
3981
3982**System capability**: SystemCapability.Multimedia.AVSession.Core
3983
3984**Parameters**
3985
3986| Name  | Type                                                        | Mandatory| Description                                                        |
3987| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3988| type     | string                                                       | Yes  | Event type, which is **'handleKeyEvent'** in this case.            |
3989| callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | No  | Callback used for unsubscription. The **event** parameter in the callback indicates the key event.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                             |
3990
3991**Error codes**
3992
3993For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
3994
3995| ID| Error Message|
3996| -------- | ---------------------------------------- |
3997| 6600101  | Session service exception. |
3998| 6600102  | The session does not exist. |
3999
4000**Example**
4001
4002```ts
4003currentAVSession.off('handleKeyEvent');
4004```
4005
4006### off('outputDeviceChange')<sup>10+</sup>
4007
4008off(type: 'outputDeviceChange', callback?: (state: ConnectionState, device: OutputDeviceInfo) => void): void
4009
4010Unsubscribes from playback device change events.
4011
4012**System capability**: SystemCapability.Multimedia.AVSession.Core
4013
4014**Parameters**
4015
4016| Name  | Type                                                   | Mandatory| Description                                                     |
4017| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------ |
4018| type     | string                                                  | Yes  | Event type, which is **'outputDeviceChange'** in this case.    |
4019| callback | (state: [ConnectionState](#connectionstate10), device: [OutputDeviceInfo](#outputdeviceinfo10)) => void | No  | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.<br>If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                       |
4020
4021**Error codes**
4022
4023For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4024
4025| ID| Error Message|
4026| -------- | ---------------------------------------- |
4027| 6600101  | Session service exception. |
4028| 6600102  | The session does not exist. |
4029
4030**Example**
4031
4032```ts
4033currentAVSession.off('outputDeviceChange');
4034```
4035
4036
4037### off('commonCommand')<sup>10+</sup>
4038
4039off(type: 'commonCommand', callback?: (command: string, args: {[key:string]: Object}) => void): void
4040
4041Unsubscribes from custom control command change events.
4042
4043**System capability**: SystemCapability.Multimedia.AVSession.Core
4044
4045**Parameters**
4046
4047| Name  | Type                                                        | Mandatory| Description                                                    |
4048| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
4049| type     | string                                                       | Yes  | Event type, which is **'commonCommand'** in this case.   |
4050| callback | (command: string, args: {[key:string]: Object}) => void         | No  | Callback used for unsubscription. The **command** parameter in the callback indicates the name of the changed custom control command, and **args** indicates the parameters carried in the command.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.                     |
4051
4052**Error codes**
4053
4054For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4055
4056| ID| Error Message|
4057| -------- | ---------------- |
4058| 6600101  | Session service exception. |
4059| 6600102  | The session does not exist. |
4060
4061**Example**
4062
4063```ts
4064currentAVSession.off('commonCommand');
4065```
4066
4067### stopCasting<sup>10+</sup>
4068
4069stopCasting(callback: AsyncCallback\<void>): void
4070
4071Stops castings. This API uses an asynchronous callback to return the result.
4072
4073**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4074
4075**Parameters**
4076
4077| Name  | Type                                 | Mandatory| Description                                 |
4078| -------- | ------------------------------------- | ---- | ------------------------------------- |
4079| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object.|
4080
4081**Error codes**
4082
4083For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4084
4085| ID| Error Message|
4086| -------- | ---------------------------------------- |
4087| 6600109  | The remote connection is not established. |
4088
4089**Example**
4090
4091```ts
4092import { BusinessError } from '@ohos.base';
4093
4094currentAVSession.stopCasting((err: BusinessError) => {
4095  if (err) {
4096    console.error(`stopCasting BusinessError: code: ${err.code}, message: ${err.message}`);
4097  } else {
4098    console.info(`stopCasting successfully`);
4099  }
4100});
4101```
4102
4103### stopCasting<sup>10+</sup>
4104
4105stopCasting(): Promise\<void>
4106
4107Stops castings. This API uses a promise to return the result.
4108
4109**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4110
4111**Return value**
4112
4113| Type          | Description                         |
4114| -------------- | ----------------------------- |
4115| Promise\<void> | Promise used to return the result. If casting stops, no value is returned; otherwise, an error object is returned.|
4116
4117**Error codes**
4118
4119For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4120
4121| ID| Error Message|
4122| -------- | ---------------------------------------- |
4123| 6600109  | The remote connection is not established. |
4124
4125**Example**
4126
4127```ts
4128import { BusinessError } from '@ohos.base';
4129
4130currentAVSession.stopCasting().then(() => {
4131  console.info(`stopCasting successfully`);
4132}).catch((err: BusinessError) => {
4133  console.error(`stopCasting BusinessError: code: ${err.code}, message: ${err.message}`);
4134});
4135```
4136
4137## AVCastControlCommandType<sup>10+</sup>
4138
4139Enumerates the commands that can be sent by a cast controller.
4140
4141**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4142
4143| Name           | Type   | Description                    |
4144| -------------- | ------ | ------------------------------ |
4145| play           | string | Play the media.                |
4146| pause          | string | Pause the playback.            |
4147| stop           | string | Stop the playback.             |
4148| playNext       | string | Play the next media asset.     |
4149| playPrevious   | string | Play the previous media asset. |
4150| fastForward    | string | Fast-forward.                  |
4151| rewind         | string | Rewind.                        |
4152| seek           | number | Seek to a playback position.   |
4153| setSpeed       | number | Set the playback speed.        |
4154| setLoopMode    | string | Set the loop mode.             |
4155| toggleFavorite | string | Favorite the media asset.      |
4156| setVolume      | number | Set the volume.                |
4157
4158## AVCastControlCommand<sup>10+</sup>
4159
4160Defines the command that can be sent by a cast controller.
4161
4162**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4163
4164| Name      | Type                                                         | Mandatory | Description                        |
4165| --------- | ------------------------------------------------------------ | --------- | ---------------------------------- |
4166| command   | [AVCastControlCommandType](#avcastcontrolcommandtype10)      | Yes       | Command.                           |
4167| parameter | [LoopMode](#loopmode10) &#124; string &#124; number &#124; [media.PlaybackSpeed](./js-apis-media.md#playbackspeed8) | No        | Parameters carried in the command. |
4168
4169## AVCastController<sup>10+</sup>
4170
4171After a casting connection is set up, you can call [avSession.getAVCastController](#getavcastcontroller10) to obtain the cast controller. Through the controller, you can query the session ID, send commands and events to a session, and obtain session metadata and playback state information.
4172
4173### setDisplaySurface<sup>10+</sup>
4174
4175setDisplaySurface(surfaceId: string): Promise\<void>
4176
4177Sets the surface ID for playback, which is used at the cast receiver (sink). This API uses a promise to return the result.
4178
4179**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4180
4181**System API**: This is a system API.
4182
4183**Return value**
4184
4185| Type           | Description                        |
4186| -------------- | ---------------------------------- |
4187| Promise\<void> | Promise used to return the result. |
4188
4189**Error codes**
4190
4191For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4192
4193| ID      | Error Message                             |
4194| ------- | ----------------------------------------- |
4195| 6600109 | The remote connection is not established. |
4196
4197**Example**
4198
4199```ts
4200import media from '@ohos.multimedia.media';
4201let surfaceID: string = '';
4202media.createAVRecorder().then((avRecorder) => {
4203  avRecorder.getInputSurface((err: BusinessError, surfaceId: string) => {
4204    if (err == null) {
4205      console.info('getInputSurface success');
4206      surfaceID = surfaceId;
4207    } else {
4208      console.error('getInputSurface failed and error is ' + err.message);
4209    }
4210  });
4211})
4212aVCastController.setDisplaySurface(surfaceID).then(() => {
4213  console.info(`setDisplaySurface : SUCCESS`);
4214});
4215```
4216
4217### setDisplaySurface<sup>10+</sup>
4218
4219setDisplaySurface(surfaceId: string, callback: AsyncCallback\<void>): void
4220
4221Sets the surface ID for playback, which is used at the cast receiver (sink). This API uses an asynchronous callback to return the result.
4222
4223**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4224
4225**System API**: This is a system API.
4226
4227**Parameters**
4228
4229| Name      | Type                 | Mandatory | Description                         |
4230| --------- | -------------------- | --------- | ----------------------------------- |
4231| callback  | AsyncCallback\<void> | Yes       | Callback used to return the result. |
4232| surfaceId | string               | Yes       | Surface ID.                         |
4233
4234
4235**Error codes**
4236
4237For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4238
4239| ID      | Error Message                             |
4240| ------- | ----------------------------------------- |
4241| 6600109 | The remote connection is not established. |
4242
4243**Example**
4244
4245```ts
4246import { BusinessError } from '@ohos.base';
4247import media from '@ohos.multimedia.media';
4248let surfaceID: string = '';
4249media.createAVRecorder().then((avRecorder) => {
4250  avRecorder.getInputSurface((err: BusinessError, surfaceId: string) => {
4251    if (err == null) {
4252      console.info('getInputSurface success');
4253      surfaceID = surfaceId;
4254    } else {
4255      console.error('getInputSurface failed and error is ' + err.message);
4256    }
4257  });
4258})
4259aVCastController.setDisplaySurface(surfaceID, (err: BusinessError) => {
4260  if (err) {
4261    console.error(`setDisplaySurface BusinessError: code: ${err.code}, message: ${err.message}`);
4262  } else {
4263    console.info(`setDisplaySurface : SUCCESS`);
4264  }
4265});
4266```
4267
4268### getAVPlaybackState<sup>10+</sup>
4269
4270getAVPlaybackState(callback: AsyncCallback\<AVPlaybackState>): void
4271
4272Obtains the remote playback state. This API uses an asynchronous callback to return the result.
4273
4274**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4275
4276**Parameters**
4277
4278| Name     | Type                                                   | Mandatory | Description                                        |
4279| -------- | ------------------------------------------------------ | --------- | -------------------------------------------------- |
4280| callback | AsyncCallback<[[AVPlaybackState](#avplaybackstate10)\> | Yes       | Callback used to return the remote playback state. |
4281
4282**Error codes**
4283
4284For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4285
4286| ID      | Error Message             |
4287| ------- | ------------------------- |
4288| 6600101 | Session service exception |
4289
4290**Example**
4291
4292```ts
4293import { BusinessError } from '@ohos.base';
4294
4295aVCastController.getAVPlaybackState((err: BusinessError, state: avSession.AVPlaybackState) => {
4296  if (err) {
4297    console.error(`getAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
4298  } else {
4299    console.info(`getAVPlaybackState : SUCCESS`);
4300  }
4301});
4302```
4303
4304### getAVPlaybackState<sup>10+</sup>
4305
4306getAVPlaybackState(): Promise\<AVPlaybackState>
4307
4308Obtains the remote playback state. This API uses a promise to return the result.
4309
4310**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4311
4312**Return value**
4313
4314| Type                                            | Description                                       |
4315| ----------------------------------------------- | ------------------------------------------------- |
4316| Promise<[AVPlaybackState](#avplaybackstate10)\> | Promise used to return the remote playback state. |
4317
4318**Error codes**
4319
4320For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4321
4322| ID      | Error Message             |
4323| ------- | ------------------------- |
4324| 6600101 | Session service exception |
4325
4326**Example**
4327
4328```ts
4329import { BusinessError } from '@ohos.base';
4330
4331aVCastController.getAVPlaybackState().then((state: avSession.AVPlaybackState) => {
4332  console.info(`getAVPlaybackState : SUCCESS`);
4333}).catch((err: BusinessError) => {
4334  console.error(`getAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
4335});
4336```
4337
4338### sendControlCommand<sup>10+</sup>
4339
4340sendControlCommand(command: AVCastControlCommand): Promise\<void>
4341
4342Sends a control command to the session through the controller. This API uses a promise to return the result.
4343
4344
4345**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4346
4347**Parameters**
4348
4349| Name    | Type                                            | Mandatory | Description      |
4350| ------- | ----------------------------------------------- | --------- | ---------------- |
4351| command | [AVCastControlCommand](#avcastcontrolcommand10) | Yes       | Command to send. |
4352
4353**Return value**
4354
4355| Type           | Description                                                  |
4356| -------------- | ------------------------------------------------------------ |
4357| Promise\<void> | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned. |
4358
4359**Error codes**
4360
4361For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4362
4363| ID      | Error Message                             |
4364| ------- | ----------------------------------------- |
4365| 6600101 | Session service exception.                |
4366| 6600105 | Invalid session command.                  |
4367| 6600109 | The remote connection is not established. |
4368
4369**Example**
4370
4371```ts
4372import avSession from '@ohos.multimedia.avsession';
4373import { BusinessError } from '@ohos.base';
4374
4375let avCommand: avSession.AVCastControlCommand = {command:'play'};
4376aVCastController.sendControlCommand(avCommand).then(() => {
4377  console.info(`SendControlCommand successfully`);
4378}).catch((err: BusinessError) => {
4379  console.error(`SendControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
4380});
4381```
4382
4383### sendControlCommand<sup>10+</sup>
4384
4385sendControlCommand(command: AVCastControlCommand, callback: AsyncCallback\<void>): void
4386
4387Sends a control command to the session through the controller. This API uses an asynchronous callback to return the result.
4388
4389
4390**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4391
4392**Parameters**
4393
4394| Name     | Type                                            | Mandatory | Description                                                  |
4395| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ |
4396| command  | [AVCastControlCommand](#avcastcontrolcommand10) | Yes       | Command to send.                                             |
4397| callback | AsyncCallback\<void>                            | Yes       | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. |
4398
4399**Error codes**
4400
4401For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4402
4403| ID      | Error Message                             |
4404| ------- | ----------------------------------------- |
4405| 6600101 | Session service exception.                |
4406| 6600105 | Invalid session command.                  |
4407| 6600109 | The remote connection is not established. |
4408
4409**Example**
4410
4411```ts
4412import avSession from '@ohos.multimedia.avsession';
4413import { BusinessError } from '@ohos.base';
4414
4415let avCommand: avSession.AVCastControlCommand = {command:'play'};
4416aVCastController.sendControlCommand(avCommand, (err: BusinessError) => {
4417  if (err) {
4418    console.error(`SendControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
4419  } else {
4420    console.info(`SendControlCommand successfully`);
4421  }
4422});
4423```
4424
4425### prepare<sup>10+</sup>
4426
4427prepare(item: AVQueueItem, callback: AsyncCallback\<void>): void
4428
4429Prepares for the playback of a media asset, that is, loads and buffers a media asset. This API uses an asynchronous callback to return the result.
4430
4431**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4432
4433**Parameters**
4434
4435| Name     | Type                          | Mandatory | Description                                                  |
4436| -------- | ----------------------------- | --------- | ------------------------------------------------------------ |
4437| item     | [AVQueueItem](#avqueueitem10) | Yes       | Attributes of an item in the playlist.                       |
4438| callback | AsyncCallback\<void>          | Yes       | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. |
4439
4440**Error codes**
4441
4442For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4443
4444| ID      | Error Message                             |
4445| ------- | ----------------------------------------- |
4446| 6600101 | Session service exception.                |
4447| 6600109 | The remote connection is not established. |
4448
4449**Example**
4450
4451```ts
4452import avSession from '@ohos.multimedia.avsession';
4453import { BusinessError } from '@ohos.base';
4454
4455// Set playback parameters.
4456let playItem: avSession.AVQueueItem = {
4457  itemId: 0,
4458  description: {
4459    assetId: '12345',
4460    mediaType: 'AUDIO',
4461    mediaUri: 'http://resource1_address',
4462    mediaSize: 12345,
4463    startPosition: 0,
4464    duration: 0,
4465    artist: 'mysong',
4466    albumTitle: 'song1_title',
4467    albumCoverUri: "http://resource1_album_address",
4468    lyricUri: "http://resource1_lyric_address",
4469    appName: 'MyMusic'
4470  }
4471};
4472// Prepare for playback. This operation triggers loading and buffering, but not the actual playback.
4473aVCastController.prepare(playItem, (err: BusinessError) => {
4474  if (err) {
4475    console.error(`prepare BusinessError: code: ${err.code}, message: ${err.message}`);
4476  } else {
4477    console.info(`prepare successfully`);
4478  }
4479});
4480```
4481
4482
4483### prepare<sup>10+</sup>
4484
4485prepare(item: AVQueueItem): Promise\<void>
4486
4487Prepares for the playback of a media asset, that is, loads and buffers a media asset. This API uses a promise to return the result.
4488
4489
4490**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4491
4492**Parameters**
4493
4494| Name | Type                          | Mandatory | Description                            |
4495| ---- | ----------------------------- | --------- | -------------------------------------- |
4496| item | [AVQueueItem](#avqueueitem10) | Yes       | Attributes of an item in the playlist. |
4497
4498**Return value**
4499
4500| Type           | Description                                                  |
4501| -------------- | ------------------------------------------------------------ |
4502| Promise\<void> | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned. |
4503
4504**Error codes**
4505
4506For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4507
4508| ID      | Error Message                             |
4509| ------- | ----------------------------------------- |
4510| 6600101 | Session service exception.                |
4511| 6600109 | The remote connection is not established. |
4512
4513
4514**Example**
4515
4516```ts
4517import avSession from '@ohos.multimedia.avsession';
4518import { BusinessError } from '@ohos.base';
4519
4520// Set playback parameters.
4521let playItem: avSession.AVQueueItem = {
4522  itemId: 0,
4523  description: {
4524    assetId: '12345',
4525    mediaType: 'AUDIO',
4526    mediaUri: 'http://resource1_address',
4527    mediaSize: 12345,
4528    startPosition: 0,
4529    duration: 0,
4530    artist: 'mysong',
4531    albumTitle: 'song1_title',
4532    albumCoverUri: "http://resource1_album_address",
4533    lyricUri: "http://resource1_lyric_address",
4534    appName: 'MyMusic'
4535  }
4536};
4537// Prepare for playback. This operation triggers loading and buffering, but not the actual playback.
4538aVCastController.prepare(playItem).then(() => {
4539  console.info(`prepare successfully`);
4540}).catch((err: BusinessError) => {
4541  console.error(`prepare BusinessError: code: ${err.code}, message: ${err.message}`);
4542});
4543```
4544
4545### start<sup>10+</sup>
4546
4547start(item: AVQueueItem, callback: AsyncCallback\<void>): void
4548
4549Prepares for the playback of a media asset. This API uses an asynchronous callback to return the result.
4550
4551**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4552
4553**Parameters**
4554
4555| Name     | Type                          | Mandatory | Description                                                  |
4556| -------- | ----------------------------- | --------- | ------------------------------------------------------------ |
4557| item     | [AVQueueItem](#avqueueitem10) | Yes       | Attributes of an item in the playlist.                       |
4558| callback | AsyncCallback\<void>          | Yes       | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. |
4559
4560**Error codes**
4561
4562For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4563
4564| ID      | Error Message                             |
4565| ------- | ----------------------------------------- |
4566| 6600101 | Session service exception.                |
4567| 6600109 | The remote connection is not established. |
4568
4569**Example**
4570
4571```ts
4572import avSession from '@ohos.multimedia.avsession';
4573import { BusinessError } from '@ohos.base';
4574
4575// Set playback parameters.
4576let playItem: avSession.AVQueueItem = {
4577  itemId: 0,
4578  description: {
4579    assetId: '12345',
4580    mediaType: 'AUDIO',
4581    mediaUri: 'http://resource1_address',
4582    mediaSize: 12345,
4583    startPosition: 0,
4584    duration: 0,
4585    artist: 'mysong',
4586    albumTitle: 'song1_title',
4587    albumCoverUri: "http://resource1_album_address",
4588    lyricUri: "http://resource1_lyric_address",
4589    appName: 'MyMusic'
4590  }
4591};
4592
4593// Start playback.
4594aVCastController.start(playItem, (err: BusinessError) => {
4595  if (err) {
4596    console.error(`start BusinessError: code: ${err.code}, message: ${err.message}`);
4597  } else {
4598    console.info(`start successfully`);
4599  }
4600});
4601
4602```
4603
4604### start<sup>10+</sup>
4605
4606start(item: AVQueueItem): Promise\<void>
4607
4608Prepares for the playback of a media asset. This API uses a promise to return the result.
4609
4610
4611**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4612
4613**Parameters**
4614
4615| Name | Type                          | Mandatory | Description                            |
4616| ---- | ----------------------------- | --------- | -------------------------------------- |
4617| item | [AVQueueItem](#avqueueitem10) | Yes       | Attributes of an item in the playlist. |
4618
4619**Return value**
4620
4621| Type           | Description                                                  |
4622| -------------- | ------------------------------------------------------------ |
4623| Promise\<void> | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned. |
4624
4625**Error codes**
4626
4627For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4628
4629| ID      | Error Message                             |
4630| ------- | ----------------------------------------- |
4631| 6600101 | Session service exception.                |
4632| 6600109 | The remote connection is not established. |
4633
4634
4635**Example**
4636
4637```ts
4638import avSession from '@ohos.multimedia.avsession';
4639import { BusinessError } from '@ohos.base';
4640
4641// Set playback parameters.
4642let playItem: avSession.AVQueueItem = {
4643  itemId: 0,
4644  description: {
4645    assetId: '12345',
4646    mediaType: 'AUDIO',
4647    mediaUri: 'http://resource1_address',
4648    mediaSize: 12345,
4649    startPosition: 0,
4650    duration: 0,
4651    artist: 'mysong',
4652    albumTitle: 'song1_title',
4653    albumCoverUri: "http://resource1_album_address",
4654    lyricUri: "http://resource1_lyric_address",
4655    appName: 'MyMusic'
4656  }
4657};
4658// Start playback.
4659aVCastController.start(playItem).then(() => {
4660  console.info(`start successfully`);
4661}).catch((err: BusinessError) => {
4662  console.error(`start BusinessError: code: ${err.code}, message: ${err.message}`);
4663});
4664
4665```
4666
4667### getCurrentItem<sup>10+</sup>
4668
4669getCurrentItem(callback: AsyncCallback\<AVQueueItem>): void
4670
4671Obtains the information about the media asset that is being played. This API uses an asynchronous callback to return the result.
4672
4673**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4674
4675**Parameters**
4676
4677| Name     | Type                                          | Mandatory | Description                                                  |
4678| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ |
4679| callback | AsyncCallback\<[AVQueueItem](#avqueueitem10)> | Yes       | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. |
4680
4681**Error codes**
4682
4683For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4684
4685| ID      | Error Message              |
4686| ------- | -------------------------- |
4687| 6600101 | Session service exception. |
4688
4689**Example**
4690
4691```ts
4692import { BusinessError } from '@ohos.base';
4693
4694aVCastController.getCurrentItem((err: BusinessError, value: avSession.AVQueueItem) => {
4695  if (err) {
4696    console.error(`getCurrentItem BusinessError: code: ${err.code}, message: ${err.message}`);
4697  } else {
4698    console.info(`getCurrentItem successfully`);
4699  }
4700});
4701
4702```
4703
4704### getCurrentItem<sup>10+</sup>
4705
4706getCurrentItem(): Promise\<AVQueueItem>
4707
4708Obtains the information about the media asset that is being played. This API uses a promise to return the result.
4709
4710**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4711
4712**Return value**
4713
4714| Type                                    | Description                                                  |
4715| --------------------------------------- | ------------------------------------------------------------ |
4716| Promise\<[AVQueueItem](#avqueueitem10)> | Promise used to return the media asset obtained. If the operation fails, an error object is returned. |
4717
4718**Error codes**
4719
4720For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4721
4722| ID      | Error Message              |
4723| ------- | -------------------------- |
4724| 6600101 | Session service exception. |
4725
4726**Example**
4727
4728```ts
4729import { BusinessError } from '@ohos.base';
4730
4731aVCastController.getCurrentItem().then((value: avSession.AVQueueItem) => {
4732  console.info(`getCurrentItem successfully`);
4733}).catch((err: BusinessError) => {
4734  console.error(`getCurrentItem BusinessError: code: ${err.code}, message: ${err.message}`);
4735});
4736
4737```
4738
4739### on('playbackStateChange')<sup>10+</sup>
4740
4741on(type: 'playbackStateChange', filter: Array\<keyof AVPlaybackState> | 'all', callback: (state: AVPlaybackState) => void): void
4742
4743Subscribes to playback state change events.
4744
4745**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4746
4747**Parameters**
4748
4749| Name     | Type                                                         | Mandatory | Description                                                  |
4750| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
4751| type     | string                                                       | Yes       | Event type. The event **'playbackStateChange'** is triggered when the playback state changes. |
4752| filter   | Array\<keyof&nbsp;[AVPlaybackState](#avplaybackstate10)\>&nbsp;&#124;&nbsp;'all' | Yes       | The value **'all'** indicates that any playback state field change will trigger the event, and **Array<keyof&nbsp;[AVPlaybackState](#avplaybackstate10)\>** indicates that only changes to the listed playback state field will trigger the event. |
4753| callback | (state: [AVPlaybackState](#avplaybackstate10)) => void       | Yes       | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state. |
4754
4755**Error codes**
4756
4757For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4758
4759| ID      | Error Message              |
4760| ------- | -------------------------- |
4761| 6600101 | Session service exception. |
4762
4763**Example**
4764
4765```ts
4766aVCastController.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
4767  console.info(`on playbackStateChange state : ${playbackState.state}`);
4768});
4769
4770let playbackFilter = ['state', 'speed', 'loopMode'];
4771aVCastController.on('playbackStateChange', playbackFilter, (playbackState: avSession.AVPlaybackState) => {
4772  console.info(`on playbackStateChange state : ${playbackState.state}`);
4773});
4774```
4775
4776### off('playbackStateChange')<sup>10+</sup>
4777
4778off(type: 'playbackStateChange', callback?: (state: AVPlaybackState) => void): void
4779
4780Unsubscribes from playback state change events. This API is called by the controller.
4781
4782**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4783
4784**Parameters**
4785
4786| Name     | Type                                                   | Mandatory | Description                                                  |
4787| -------- | ------------------------------------------------------ | --------- | ------------------------------------------------------------ |
4788| type     | string                                                 | Yes       | Event type, which is **'playbackStateChange'** in this case. |
4789| callback | (state: [AVPlaybackState](#avplaybackstate10)) => void | No        | Callback used for unsubscription. The **state** parameter in the callback indicates the changed playback state.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. |
4790
4791**Error codes**
4792
4793For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4794
4795| ID      | Error Message              |
4796| ------- | -------------------------- |
4797| 6600101 | Session service exception. |
4798
4799**Example**
4800
4801```ts
4802aVCastController.off('playbackStateChange');
4803
4804```
4805
4806### on('mediaItemChange')<sup>10+</sup>
4807
4808on(type: 'mediaItemChange', callback: Callback\<AVQueueItem>): void
4809
4810Subscribes to media asset change events.
4811
4812**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4813
4814**Parameters**
4815
4816| Name     | Type                                              | Mandatory | Description                                                  |
4817| -------- | ------------------------------------------------- | --------- | ------------------------------------------------------------ |
4818| type     | string                                            | Yes       | Event type. The event **'mediaItemChange'** is triggered when the media content being played changes. |
4819| callback | (callback: [AVQueueItem](#avqueueitem10)) => void | Yes       | Callback used for subscription. **AVQueueItem** is the media asset that is being played. |
4820
4821**Error codes**
4822
4823For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4824
4825| ID      | Error Message              |
4826| ------- | -------------------------- |
4827| 6600101 | Session service exception. |
4828
4829**Example**
4830
4831```ts
4832aVCastController.on('mediaItemChange', (item: avSession.AVQueueItem) => {
4833  console.info(`on mediaItemChange state : ${item.itemId}`);
4834});
4835
4836```
4837
4838### off('mediaItemChange')<sup>10+</sup>
4839
4840off(type: 'mediaItemChange'): void
4841
4842Unsubscribes from media asset change events.
4843
4844**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4845
4846**Parameters**
4847
4848| Name | Type   | Mandatory | Description                                              |
4849| ---- | ------ | --------- | -------------------------------------------------------- |
4850| type | string | Yes       | Event type, which is **'mediaItemChange'** in this case. |
4851
4852**Error codes**
4853
4854For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4855
4856| ID      | Error Message              |
4857| ------- | -------------------------- |
4858| 6600101 | Session service exception. |
4859
4860**Example**
4861
4862```ts
4863aVCastController.off('mediaItemChange');
4864
4865```
4866
4867### on('playNext')<sup>10+</sup>
4868
4869on(type: 'playNext', callback: Callback\<void>): void
4870
4871Subscribes to playNext command events.
4872
4873**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4874
4875**Parameters**
4876
4877| Name     | Type             | Mandatory | Description                                                  |
4878| -------- | ---------------- | --------- | ------------------------------------------------------------ |
4879| type     | string           | Yes       | Event type. The event **'playNext'** is triggered when the command for playing the next item is received. |
4880| callback | Callback\<void\> | Yes       | Callback used to return the result.                          |
4881
4882**Error codes**
4883
4884For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4885
4886| ID      | Error Message              |
4887| ------- | -------------------------- |
4888| 6600101 | Session service exception. |
4889
4890**Example**
4891
4892```ts
4893aVCastController.on('playNext', () => {
4894  console.info(`on playNext`);
4895});
4896
4897```
4898
4899### off('playNext')<sup>10+</sup>
4900
4901off(type: 'playNext'): void
4902
4903Unsubscribes from playNext command events.
4904
4905**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4906
4907**Parameters**
4908
4909| Name | Type   | Mandatory | Description                                       |
4910| ---- | ------ | --------- | ------------------------------------------------- |
4911| type | string | Yes       | Event type, which is **'playNext'** in this case. |
4912
4913**Error codes**
4914
4915For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4916
4917| ID      | Error Message              |
4918| ------- | -------------------------- |
4919| 6600101 | Session service exception. |
4920
4921**Example**
4922
4923```ts
4924aVCastController.off('playNext');
4925
4926```
4927
4928### on('playPrevious')<sup>10+</sup>
4929
4930on(type: 'playPrevious', callback: Callback\<void>): void
4931
4932Subscribes to playPrevious command events.
4933
4934**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4935
4936**Parameters**
4937
4938| Name     | Type             | Mandatory | Description                                                  |
4939| -------- | ---------------- | --------- | ------------------------------------------------------------ |
4940| type     | string           | Yes       | Event type. The event **'playPrevious'** is triggered when the command for playing the previous event is received. |
4941| callback | Callback\<void\> | Yes       | Callback used to return the result.                          |
4942
4943**Error codes**
4944
4945For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4946
4947| ID      | Error Message              |
4948| ------- | -------------------------- |
4949| 6600101 | Session service exception. |
4950
4951**Example**
4952
4953```ts
4954aVCastController.on('playPrevious', () => {
4955  console.info(`on playPrevious`);
4956});
4957
4958```
4959
4960### off('playPrevious')<sup>10+</sup>
4961
4962off(type: 'playPrevious'): void
4963
4964Unsubscribes from playPrevious command events.
4965
4966**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4967
4968**Parameters**
4969
4970| Name | Type   | Mandatory | Description                                           |
4971| ---- | ------ | --------- | ----------------------------------------------------- |
4972| type | string | Yes       | Event type, which is **'playPrevious'** in this case. |
4973
4974**Error codes**
4975
4976For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
4977
4978| ID      | Error Message              |
4979| ------- | -------------------------- |
4980| 6600101 | Session service exception. |
4981
4982**Example**
4983
4984```ts
4985aVCastController.off('playPrevious');
4986```
4987
4988### on('seekDone')<sup>10+</sup>
4989
4990on(type: 'seekDone', callback: Callback\<number>): void
4991
4992Subscribes to seek done events.
4993
4994**System capability**: SystemCapability.Multimedia.AVSession.AVCast
4995
4996**Parameters**
4997
4998| Name     | Type               | Mandatory | Description                                                  |
4999| -------- | ------------------ | --------- | ------------------------------------------------------------ |
5000| type     | string             | Yes       | Event type. The event **'seekDone'** is triggered when the seek operation is complete. |
5001| callback | Callback\<number\> | Yes       | Callback used to return the position after the seek operation. |
5002
5003**Error codes**
5004
5005For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5006
5007| ID      | Error Message              |
5008| ------- | -------------------------- |
5009| 6600101 | Session service exception. |
5010
5011**Example**
5012
5013```ts
5014aVCastController.on('seekDone', (pos: number) => {
5015  console.info(`on seekDone pos: ${pos} `);
5016});
5017
5018```
5019
5020### off('seekDone')<sup>10+</sup>
5021
5022off(type: 'seekDone'): void
5023
5024Unsubscribes from the seek done events.
5025
5026**System capability**: SystemCapability.Multimedia.AVSession.AVCast
5027
5028**Parameters**
5029
5030| Name | Type   | Mandatory | Description                                       |
5031| ---- | ------ | --------- | ------------------------------------------------- |
5032| type | string | Yes       | Event type, which is **'seekDone'** in this case. |
5033
5034**Error codes**
5035
5036For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5037
5038| ID      | Error Message              |
5039| ------- | -------------------------- |
5040| 6600101 | Session service exception. |
5041
5042**Example**
5043
5044```ts
5045aVCastController.off('seekDone');
5046```
5047
5048### on('videoSizeChange')<sup>10+</sup>
5049
5050on(type: 'videoSizeChange', callback: (width:number, height:number) => void): void
5051
5052Subscribes to video size change events.
5053
5054**System capability**: SystemCapability.Multimedia.AVSession.AVCast
5055
5056**System API**: This is a system API.
5057
5058**Parameters**
5059
5060| Name     | Type                                  | Mandatory | Description                                                  |
5061| -------- | ------------------------------------- | --------- | ------------------------------------------------------------ |
5062| type     | string                                | Yes       | Event type. The event **'videoSizeChange'** is triggered when the video size changes. |
5063| callback | (width:number, height:number) => void | Yes       | Callback used to return the video width and height.          |
5064
5065**Error codes**
5066
5067For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5068
5069| ID      | Error Message              |
5070| ------- | -------------------------- |
5071| 6600101 | Session service exception. |
5072
5073**Example**
5074
5075```ts
5076aVCastController.on('videoSizeChange', (width: number, height: number) => {
5077  console.info(`width : ${width} `);
5078  console.info(`height: ${height} `);
5079});
5080
5081```
5082
5083### off('videoSizeChange')<sup>10+</sup>
5084
5085off(type: 'videoSizeChange'): void
5086
5087Unsubscribes from video size changes.
5088
5089**System capability**: SystemCapability.Multimedia.AVSession.AVCast
5090
5091**System API**: This is a system API.
5092
5093**Parameters**
5094
5095| Name | Type   | Mandatory | Description                                              |
5096| ---- | ------ | --------- | -------------------------------------------------------- |
5097| type | string | Yes       | Event type, which is **'videoSizeChange'** in this case. |
5098
5099**Error codes**
5100
5101For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5102
5103| ID      | Error Message              |
5104| ------- | -------------------------- |
5105| 6600101 | Session service exception. |
5106
5107**Example**
5108
5109```ts
5110aVCastController.off('videoSizeChange');
5111
5112```
5113
5114### on('error')<sup>10+</sup>
5115
5116on(type: 'error', callback: ErrorCallback): void
5117
5118Subscribes to remote AVPlayer errors. This event is used only for error prompt and does not require the user to stop playback control.
5119
5120**System capability**: SystemCapability.Multimedia.AVSession.AVCast
5121
5122**Parameters**
5123
5124| Name     | Type          | Mandatory | Description                                                  |
5125| -------- | ------------- | --------- | ------------------------------------------------------------ |
5126| type     | string        | Yes       | Event type, which is **'error'** in this case. This event can be triggered by both user operations and the system. |
5127| callback | ErrorCallback | Yes       | Callback used to return the error code ID and error message. |
5128
5129**Error codes**
5130
5131For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md).
5132
5133| ID      | Error Message              |
5134| ------- | -------------------------- |
5135| 5400101 | No memory.                 |
5136| 5400102 | Operation not allowed.     |
5137| 5400103 | I/O error.                 |
5138| 5400104 | Time out.                  |
5139| 5400105 | Service died.              |
5140| 5400106 | Unsupport format.          |
5141| 6600101 | Session service exception. |
5142
5143**Example**
5144
5145```ts
5146import { BusinessError } from '@ohos.base'
5147
5148aVCastController.on('error', (error: BusinessError) => {
5149  console.info('error happened,and error message is :' + error.message)
5150  console.info('error happened,and error code is :' + error.code)
5151})
5152
5153```
5154
5155### off('error')<sup>10+</sup>
5156
5157off(type: 'error'): void
5158
5159Unsubscribes from remote AVPlayer errors.
5160
5161**System capability**: SystemCapability.Multimedia.AVSession.AVCast
5162
5163**Parameters**
5164
5165| Name | Type   | Mandatory | Description                                    |
5166| ---- | ------ | --------- | ---------------------------------------------- |
5167| type | string | Yes       | Event type, which is **'error'** in this case. |
5168
5169**Error codes**
5170
5171For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md).
5172
5173| ID      | Error Message              |
5174| ------- | -------------------------- |
5175| 5400101 | No memory.                 |
5176| 5400102 | Operation not allowed.     |
5177| 5400103 | I/O error.                 |
5178| 5400104 | Time out.                  |
5179| 5400105 | Service died.              |
5180| 5400106 | Unsupport format.          |
5181| 6600101 | Session service exception. |
5182
5183**Example**
5184
5185```ts
5186aVCastController.off('error')
5187
5188```
5189
5190## ConnectionState<sup>10+</sup>
5191
5192Enumerates the connection states.
5193
5194**System capability**: SystemCapability.Multimedia.AVSession.Core
5195
5196| Name               | Value | Description                 |
5197| ------------------ | ----- | --------------------------- |
5198| STATE_CONNECTING   | 0     | The device is connecting.   |
5199| STATE_CONNECTED    | 1     | The device is connected.    |
5200| STATE_DISCONNECTED | 6     | The device is disconnected. |
5201
5202## AVMetadata<sup>10+</sup>
5203
5204Describes the media metadata.
5205
5206**System capability**: SystemCapability.Multimedia.AVSession.Core
5207
5208| Name                        | Type                                                         | Mandatory | Description                                                  |
5209| --------------------------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
5210| assetId                     | string                                                       | Yes       | Media asset ID.                                              |
5211| title                       | string                                                       | No        | Title.                                                       |
5212| artist                      | string                                                       | No        | Artist.                                                      |
5213| author                      | string                                                       | No        | Author.                                                      |
5214| album                       | string                                                       | No        | Album name.                                                  |
5215| writer                      | string                                                       | No        | Writer.                                                      |
5216| composer                    | string                                                       | No        | composer.                                                    |
5217| duration                    | number                                                       | No        | Media duration, in ms.                                       |
5218| mediaImage                  | image.PixelMap &#124; string                                 | No        | Pixel map or image path (local path or network path) of the image. |
5219| publishDate                 | Date                                                         | No        | Release date.                                                |
5220| subtitle                    | string                                                       | No        | Subtitle.                                                    |
5221| description                 | string                                                       | No        | Media description.                                           |
5222| lyric                       | string                                                       | No        | Lyric file path (local path or network path).                |
5223| previousAssetId             | string                                                       | No        | ID of the previous media asset.                              |
5224| nextAssetId                 | string                                                       | No        | ID of the next media asset.                                  |
5225
5226## AVMediaDescription<sup>10+</sup>
5227
5228Describes the attributes related to the media metadata in the playlist.
5229
5230**System capability**: SystemCapability.Multimedia.AVSession.Core
5231
5232| Name            | Type                   | Mandatory | Description                                                  |
5233| --------------- | ---------------------- | --------- | ------------------------------------------------------------ |
5234| assetId         | string                 | Yes       | Media ID in the playlist.                                    |
5235| title           | string                 | No        | Name of the media asset in the playlist.                     |
5236| subtitle        | string                 | No        | Subname of the media asset in the playlist.                  |
5237| description     | string                 | No        | Description of the media asset in the playlist.              |
5238| mediaImage      | image.PixelMap         | No        | Pixel map of the image of the media asset in the playlist.   |
5239| extras          | {[key: string]: any}   | No        | Additional fields of the media asset in the playlist.        |
5240| mediaUri        | string                 | No        | URI of the media asset in the playlist.                      |
5241| mediaType       | string                 | No        | Type of the media asset in the playlist.                     |
5242| mediaSize       | number                 | No        | Size of the media asset in the playlist.                     |
5243| albumTitle      | string                 | No        | Album name of the media asset in the playlist.               |
5244| albumCoverUri   | string                 | No        | URI of the album title of the media asset in the playlist.   |
5245| lyricContent    | string                 | No        | Lyric content of the media asset in the playlist.            |
5246| lyricUri        | string                 | No        | Lyric URI of the media asset in the playlist.                |
5247| artist          | string                 | No        | Author of the lyric of the media asset in the playlist.      |
5248| fdSrc           | media.AVFileDescriptor | No        | Handle to the local media file in the playlist.              |
5249| duration        | number                 | No        | Playback duration of the media asset in the playlist.        |
5250| startPosition   | number                 | No        | Start position for playing the media asset in the playlist.  |
5251| creditsPosition | number                 | No        | Position for playing the closing credits of the media asset in the playlist. |
5252| appName         | string                 | No        | Name of the application provided by the playlist.            |
5253
5254## AVQueueItem<sup>10+</sup>
5255
5256Describes the attributes of an item in the playlist.
5257
5258**System capability**: SystemCapability.Multimedia.AVSession.Core
5259
5260| Name        | Type                                        | Mandatory | Description                                 |
5261| ----------- | ------------------------------------------- | --------- | ------------------------------------------- |
5262| itemId      | number                                      | Yes       | ID of an item in the playlist.              |
5263| description | [AVMediaDescription](#avmediadescription10) | Yes        | Media metadata of the item in the playlist. |
5264
5265## AVPlaybackState<sup>10+</sup>
5266
5267Describes the information related to the media playback state.
5268
5269**System capability**: SystemCapability.Multimedia.AVSession.Core
5270
5271| Name                       | Type                                    | Mandatory | Description                                            |
5272| -------------------------- | --------------------------------------- | --------- | ------------------------------------------------------ |
5273| state                      | [PlaybackState](#playbackstate)       | No        | Playback state.                                        |
5274| speed                      | number                                  | No        | Playback speed.                                        |
5275| position                   | [PlaybackPosition](#playbackposition) | No        | Playback position.                                     |
5276| bufferedTime               | number                                  | No        | Buffered time.                                         |
5277| loopMode                   | [LoopMode](#loopmode10)                 | No        | Loop mode.                                             |
5278| isFavorite                 | boolean                                 | No        | Whether the media asset is favorited.                  |
5279| activeItemId<sup>10+</sup> | number                                  | No        | ID of the item that is being played.                   |
5280| volume<sup>10+</sup>       | number                                  | No        | Media volume.                                          |
5281| extras<sup>10+</sup>       | {[key: string]: Object}                 | No        | Custom media data.                                     |
5282| maxVolume<sup>11+</sup>    | number                                  | No        | Maximum volume.                                        |
5283| muted<sup>11+</sup>        | boolean                                 | No        | Mute status. The value **true** means the muted state. |
5284| videoWidth<sup>11+</sup>   | number                                  | No        | Video width of the media asset, in pixels.             |
5285| videoHeight<sup>11+</sup>  | number                                  | No        | Video height of the media asset, in pixels.            |
5286
5287## PlaybackPosition<sup>10+</sup>
5288
5289Describes the information related to the playback position.
5290
5291**System capability**: SystemCapability.Multimedia.AVSession.Core
5292
5293| Name        | Type   | Mandatory | Description          |
5294| ----------- | ------ | --------- | -------------------- |
5295| elapsedTime | number | Yes       | Elapsed time, in ms. |
5296| updateTime  | number | Yes       | Updated time, in ms. |
5297
5298## AVCastCategory<sup>10+</sup>
5299
5300Enumerates the cast categories.
5301
5302**System capability**: SystemCapability.Multimedia.AVSession.AVCast
5303
5304| Name            | Value | Description                                                  |
5305| --------------- | ----- | ------------------------------------------------------------ |
5306| CATEGORY_LOCAL  | 0     | Local playback. The sound is played from the local device or a connected Bluetooth headset by default. |
5307| CATEGORY_REMOTE | 1     | Remote playback. The sound or images are played from a remote device. |
5308
5309## DeviceType<sup>10+</sup>
5310
5311Enumerates the output device types.
5312
5313**System capability**: SystemCapability.Multimedia.AVSession.Core
5314
5315| Name                      | Value | Description                                                  |
5316| ------------------------- | ----- | ------------------------------------------------------------ |
5317| DEVICE_TYPE_LOCAL         | 0     | Local device.                                                |
5318| DEVICE_TYPE_BLUETOOTH     | 10    | Bluetooth device.                                            |
5319| DEVICE_TYPE_TV            | 2     | TV.<br>**System capability**: SystemCapability.Multimedia.AVSession.AVCast |
5320| DEVICE_TYPE_SMART_SPEAKER | 3     | Speaker.<br>**System capability**: SystemCapability.Multimedia.AVSession.AVCast |
5321
5322## DeviceInfo<sup>10+</sup>
5323
5324Describes the information related to the output device.
5325
5326**System capability**: SystemCapability.Multimedia.AVSession.Core
5327
5328| Name                               | Type           | Mandatory | Description                                                  |
5329| ---------------------------------- | -------------- | --------- | ------------------------------------------------------------ |
5330| castCategory                       | AVCastCategory | Yes       | Cast category.                                               |
5331| deviceId                           | string         | Yes       | ID of the output device.                                     |
5332| deviceName                         | string         | Yes       | Name of the output device.                                   |
5333| deviceType                         | DeviceType     | Yes       | Type of the output device.                                   |
5334| ipAddress                          | string         | No        | IP address of the output device.<br>This is a system API.<br>**System capability**: SystemCapability.Multimedia.AVSession.AVCast |
5335| providerId                         | number         | No        | Vendor of the output device.<br>This is a system API.<br>**System capability**: SystemCapability.Multimedia.AVSession.AVCast |
5336
5337## OutputDeviceInfo<sup>10+</sup>
5338
5339Describes the information related to the output device.
5340
5341**System capability**: SystemCapability.Multimedia.AVSession.Core
5342
5343| Name    | Type                | Mandatory | Description     |
5344| ------- | ------------------- | --------- | --------------- |
5345| devices | Array\<DeviceInfo\> | Yes       | Output devices. |
5346
5347## LoopMode<sup>10+</sup>
5348
5349Enumerates the loop modes of media playback.
5350
5351**System capability**: SystemCapability.Multimedia.AVSession.Core
5352
5353| Name                           | Value | Description          |
5354| ------------------------------ | ----- | -------------------- |
5355| LOOP_MODE_SEQUENCE             | 0     | Sequential playback. |
5356| LOOP_MODE_SINGLE               | 1     | Single loop.         |
5357| LOOP_MODE_LIST                 | 2     | Playlist loop.       |
5358| LOOP_MODE_SHUFFLE              | 3     | Shuffle.             |
5359
5360## PlaybackState<sup>10+</sup>
5361
5362Enumerates the media playback states.
5363
5364**System capability**: SystemCapability.Multimedia.AVSession.Core
5365
5366| Name                                   | Value | Description        |
5367| -------------------------------------- | ----- | ------------------ |
5368| PLAYBACK_STATE_INITIAL                 | 0     | Initial.           |
5369| PLAYBACK_STATE_PREPARE                 | 1     | Preparing.         |
5370| PLAYBACK_STATE_PLAY                    | 2     | Playing.           |
5371| PLAYBACK_STATE_PAUSE                   | 3     | Paused.            |
5372| PLAYBACK_STATE_FAST_FORWARD            | 4     | Fast-forwarding.   |
5373| PLAYBACK_STATE_REWIND                  | 5     | Rewinding.         |
5374| PLAYBACK_STATE_STOP                    | 6     | Stop the playback. |
5375| PLAYBACK_STATE_COMPLETED               | 7     | Playback complete. |
5376| PLAYBACK_STATE_RELEASED                | 8     | Released.          |
5377| PLAYBACK_STATE_ERROR                   | 9     | Error.             |
5378
5379## AVSessionDescriptor
5380
5381Declares the session descriptor.
5382
5383**System capability**: SystemCapability.Multimedia.AVSession.Manager
5384
5385**System API**: This is a system API.
5386
5387| Name         | Type             | Readable| Writable| Description |
5388| --------------| ---------------- |-----|-----|------|
5389| sessionId    | string    | Yes | No| Session ID.     |
5390| type         | [AVSessionType](#avsessiontype10)   | Yes  | No | Session type.   |
5391| sessionTag   | string             | Yes  | No | Custom session name.   |
5392| elementName  | [ElementName](js-apis-bundle-ElementName.md)  | Yes  | No | Information about the application to which the session belongs, including the bundle name and ability name.|
5393| isActive     | boolean             | Yes  | No | Whether the session is activated.                                     |
5394| isTopSession | boolean             | Yes  | No | Whether the session is the top session.                               |
5395| outputDevice | [OutputDeviceInfo](#outputdeviceinfo10)    | Yes  | No | Information about the output device.  |
5396
5397## AVSessionController<sup>10+</sup>
5398
5399An AV session controller is created by calling [avSession.createController](#avsessioncreatecontroller). Through the controller, you can query the session ID, send commands and events to a session, and obtain session metadata and playback state information.
5400
5401### Attributes
5402
5403**System capability**: SystemCapability.Multimedia.AVSession.Core
5404
5405| Name      | Type   | Readable | Writable | Description                                              |
5406| :-------- | :----- | :------- | :------- | :------------------------------------------------------- |
5407| sessionId | string | Yes      | No       | Unique session ID of the **AVSessionController** object. |
5408
5409
5410**Example**
5411
5412```ts
5413import { BusinessError } from '@ohos.base';
5414
5415let AVSessionController: avSession.AVSessionController;
5416avSession.createController(currentAVSession.sessionId).then((controller: avSession.AVSessionController) => {
5417  AVSessionController = controller;
5418}).catch((err: BusinessError) => {
5419  console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
5420});
5421
5422```
5423
5424### getAVPlaybackState<sup>10+</sup>
5425
5426getAVPlaybackState(callback: AsyncCallback\<AVPlaybackState>): void
5427
5428Obtains the remote playback state. This API uses an asynchronous callback to return the result.
5429
5430**System capability**: SystemCapability.Multimedia.AVSession.Core
5431
5432**Parameters**
5433
5434| Name     | Type                                                   | Mandatory | Description                                        |
5435| -------- | ------------------------------------------------------ | --------- | -------------------------------------------------- |
5436| callback | AsyncCallback<[[AVPlaybackState](#avplaybackstate10)\> | Yes       | Callback used to return the remote playback state. |
5437
5438**Error codes**
5439
5440For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5441
5442| ID      | Error Message                          |
5443| ------- | -------------------------------------- |
5444| 6600101 | Session service exception.             |
5445| 6600102 | The session does not exist.            |
5446| 6600103 | The session controller does not exist. |
5447
5448**Example**
5449
5450```ts
5451import { BusinessError } from '@ohos.base';
5452
5453avsessionController.getAVPlaybackState((err: BusinessError, state: avSession.AVPlaybackState) => {
5454  if (err) {
5455    console.error(`getAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
5456  } else {
5457    console.info(`getAVPlaybackState : SUCCESS`);
5458  }
5459});
5460
5461```
5462
5463### getAVPlaybackState<sup>10+</sup>
5464
5465getAVPlaybackState(): Promise\<AVPlaybackState>;
5466
5467Obtains the remote playback state. This API uses a promise to return the result.
5468
5469**System capability**: SystemCapability.Multimedia.AVSession.Core
5470
5471**Return value**
5472
5473| Type                                            | Description                                       |
5474| ----------------------------------------------- | ------------------------------------------------- |
5475| Promise<[AVPlaybackState](#avplaybackstate10)\> | Promise used to return the remote playback state. |
5476
5477**Error codes**
5478
5479For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5480
5481| ID      | Error Message                          |
5482| ------- | -------------------------------------- |
5483| 6600101 | Session service exception.             |
5484| 6600102 | The session does not exist.            |
5485| 6600103 | The session controller does not exist. |
5486
5487**Example**
5488
5489```ts
5490import { BusinessError } from '@ohos.base';
5491
5492avsessionController.getAVPlaybackState().then((state: avSession.AVPlaybackState) => {
5493  console.info(`getAVPlaybackState : SUCCESS`);
5494}).catch((err: BusinessError) => {
5495  console.error(`getAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
5496});
5497
5498```
5499
5500### getAVMetadata<sup>10+</sup>
5501
5502getAVMetadata(): Promise\<AVMetadata>
5503
5504Obtains the session metadata. This API uses a promise to return the result.
5505
5506**System capability**: SystemCapability.Multimedia.AVSession.Core
5507
5508**Return value**
5509
5510| Type                                  | Description                                   |
5511| ------------------------------------- | --------------------------------------------- |
5512| Promise<[AVMetadata](#avmetadata10)\> | Promise used to return the metadata obtained. |
5513
5514**Error codes**
5515
5516For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5517
5518| ID      | Error Message                          |
5519| ------- | -------------------------------------- |
5520| 6600101 | Session service exception.             |
5521| 6600102 | The session does not exist.            |
5522| 6600103 | The session controller does not exist. |
5523
5524**Example**
5525
5526```ts
5527import { BusinessError } from '@ohos.base';
5528
5529avsessionController.getAVMetadata().then((metadata: avSession.AVMetadata) => {
5530  console.info(`GetAVMetadata : SUCCESS : assetId : ${metadata.assetId}`);
5531}).catch((err: BusinessError) => {
5532  console.error(`GetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
5533});
5534
5535```
5536
5537### getAVMetadata<sup>10+</sup>
5538
5539getAVMetadata(callback: AsyncCallback\<AVMetadata>): void
5540
5541Obtains the session metadata. This API uses an asynchronous callback to return the result.
5542
5543**System capability**: SystemCapability.Multimedia.AVSession.Core
5544
5545**Parameters**
5546
5547| Name     | Type                                        | Mandatory | Description                                    |
5548| -------- | ------------------------------------------- | --------- | ---------------------------------------------- |
5549| callback | AsyncCallback<[AVMetadata](#avmetadata10)\> | Yes       | Callback used to return the metadata obtained. |
5550
5551**Error codes**
5552
5553For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5554
5555| ID      | Error Message                          |
5556| ------- | -------------------------------------- |
5557| 6600101 | Session service exception.             |
5558| 6600102 | The session does not exist.            |
5559| 6600103 | The session controller does not exist. |
5560
5561**Example**
5562
5563```ts
5564import { BusinessError } from '@ohos.base';
5565
5566avsessionController.getAVMetadata((err: BusinessError, metadata: avSession.AVMetadata) => {
5567  if (err) {
5568    console.error(`GetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
5569  } else {
5570    console.info(`GetAVMetadata : SUCCESS : assetId : ${metadata.assetId}`);
5571  }
5572});
5573
5574```
5575
5576### getAVQueueTitle<sup>10+</sup>
5577
5578getAVQueueTitle(): Promise\<string>
5579
5580Obtains the name of the playlist. This API uses a promise to return the result.
5581
5582**System capability**: SystemCapability.Multimedia.AVSession.Core
5583
5584**Return value**
5585
5586| Type             | Description                               |
5587| ---------------- | ----------------------------------------- |
5588| Promise<string\> | Promise used to return the playlist name. |
5589
5590**Error codes**
5591
5592For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5593
5594| ID      | Error Message                          |
5595| ------- | -------------------------------------- |
5596| 6600101 | Session service exception.             |
5597| 6600102 | The session does not exist.            |
5598| 6600103 | The session controller does not exist. |
5599
5600**Example**
5601
5602```ts
5603import { BusinessError } from '@ohos.base';
5604
5605avsessionController.getAVQueueTitle().then((title: string) => {
5606  console.info(`GetAVQueueTitle : SUCCESS : title : ${title}`);
5607}).catch((err: BusinessError) => {
5608  console.error(`GetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`);
5609});
5610
5611```
5612
5613### getAVQueueTitle<sup>10+</sup>
5614
5615getAVQueueTitle(callback: AsyncCallback\<string>): void
5616
5617Obtains the name of the playlist. This API uses an asynchronous callback to return the result.
5618
5619**System capability**: SystemCapability.Multimedia.AVSession.Core
5620
5621**Parameters**
5622
5623| Name     | Type                   | Mandatory | Description                                |
5624| -------- | ---------------------- | --------- | ------------------------------------------ |
5625| callback | AsyncCallback<string\> | Yes       | Callback used to return the playlist name. |
5626
5627**Error codes**
5628
5629For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5630
5631| ID      | Error Message                          |
5632| ------- | -------------------------------------- |
5633| 6600101 | Session service exception.             |
5634| 6600102 | The session does not exist.            |
5635| 6600103 | The session controller does not exist. |
5636
5637**Example**
5638
5639```ts
5640import { BusinessError } from '@ohos.base';
5641
5642avsessionController.getAVQueueTitle((err: BusinessError, title: string) => {
5643  if (err) {
5644    console.error(`GetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`);
5645  } else {
5646    console.info(`GetAVQueueTitle : SUCCESS : title : ${title}`);
5647  }
5648});
5649
5650```
5651
5652### getAVQueueItems<sup>10+</sup>
5653
5654getAVQueueItems(): Promise\<Array\<AVQueueItem>>
5655
5656Obtains the information related to the items in the queue. This API uses a promise to return the result.
5657
5658**System capability**: SystemCapability.Multimedia.AVSession.Core
5659
5660**Return value**
5661
5662| Type                                            | Description                                    |
5663| ----------------------------------------------- | ---------------------------------------------- |
5664| Promise<Array<[AVQueueItem](#avqueueitem10)\>\> | Promise used to return the items in the queue. |
5665
5666**Error codes**
5667
5668For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5669
5670| ID      | Error Message                          |
5671| ------- | -------------------------------------- |
5672| 6600101 | Session service exception.             |
5673| 6600102 | The session does not exist.            |
5674| 6600103 | The session controller does not exist. |
5675
5676**Example**
5677
5678```ts
5679import { BusinessError } from '@ohos.base';
5680
5681avsessionController.getAVQueueItems().then((items: avSession.AVQueueItem[]) => {
5682  console.info(`GetAVQueueItems : SUCCESS : length : ${items.length}`);
5683}).catch((err: BusinessError) => {
5684  console.error(`GetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`);
5685});
5686
5687```
5688
5689### getAVQueueItems<sup>10+</sup>
5690
5691getAVQueueItems(callback: AsyncCallback\<Array\<AVQueueItem>>): void
5692
5693Obtains the information related to the items in the playlist. This API uses an asynchronous callback to return the result.
5694
5695**System capability**: SystemCapability.Multimedia.AVSession.Core
5696
5697**Parameters**
5698
5699| Name     | Type                                                  | Mandatory | Description                                        |
5700| -------- | ----------------------------------------------------- | --------- | -------------------------------------------------- |
5701| callback | AsyncCallback<Array<[AVQueueItem](#avqueueitem10)\>\> | Yes       | Callback used to return the items in the playlist. |
5702
5703**Error codes**
5704
5705For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5706
5707| ID      | Error Message                          |
5708| ------- | -------------------------------------- |
5709| 6600101 | Session service exception.             |
5710| 6600102 | The session does not exist.            |
5711| 6600103 | The session controller does not exist. |
5712
5713**Example**
5714
5715```ts
5716import { BusinessError } from '@ohos.base';
5717
5718avsessionController.getAVQueueItems((err: BusinessError, items: avSession.AVQueueItem[]) => {
5719  if (err) {
5720    console.error(`GetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`);
5721  } else {
5722    console.info(`GetAVQueueItems : SUCCESS : length : ${items.length}`);
5723  }
5724});
5725
5726```
5727
5728### skipToQueueItem<sup>10+</sup>
5729
5730skipToQueueItem(itemId: number): Promise\<void>
5731
5732Sends 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.
5733
5734**System capability**: SystemCapability.Multimedia.AVSession.Core
5735
5736**Parameters**
5737
5738| Name   | Type   | Mandatory | Description                    |
5739| ------ | ------ | --------- | ------------------------------ |
5740| itemId | number | Yes       | ID of an item in the playlist. |
5741
5742**Return value**
5743
5744| Type           | Description                                                  |
5745| -------------- | ------------------------------------------------------------ |
5746| Promise\<void> | Promise used to return the result. If the item ID is sent, no value is returned; otherwise, an error object is returned. |
5747
5748**Error codes**
5749
5750For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5751
5752| ID      | Error Message                          |
5753| ------- | -------------------------------------- |
5754| 6600101 | Session service exception.             |
5755| 6600102 | The session does not exist.            |
5756| 6600103 | The session controller does not exist. |
5757
5758**Example**
5759
5760```ts
5761import { BusinessError } from '@ohos.base';
5762
5763let queueItemId = 0;
5764avsessionController.skipToQueueItem(queueItemId).then(() => {
5765  console.info(`SkipToQueueItem successfully`);
5766}).catch((err: BusinessError) => {
5767  console.error(`SkipToQueueItem BusinessError: code: ${err.code}, message: ${err.message}`);
5768});
5769
5770```
5771
5772### skipToQueueItem<sup>10+</sup>
5773
5774skipToQueueItem(itemId: number, callback: AsyncCallback\<void>): void
5775
5776Sends 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.
5777
5778**System capability**: SystemCapability.Multimedia.AVSession.Core
5779
5780**Parameters**
5781
5782| Name     | Type                 | Mandatory | Description                                                  |
5783| -------- | -------------------- | --------- | ------------------------------------------------------------ |
5784| itemId   | number               | Yes       | ID of an item in the playlist.                               |
5785| callback | AsyncCallback\<void> | Yes       | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object. |
5786
5787**Error codes**
5788
5789For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5790
5791| ID      | Error Message                          |
5792| ------- | -------------------------------------- |
5793| 6600101 | Session service exception.             |
5794| 6600102 | The session does not exist.            |
5795| 6600103 | The session controller does not exist. |
5796
5797**Example**
5798
5799```ts
5800import { BusinessError } from '@ohos.base';
5801
5802let queueItemId = 0;
5803avsessionController.skipToQueueItem(queueItemId, (err: BusinessError) => {
5804  if (err) {
5805    console.error(`SkipToQueueItem BusinessError: code: ${err.code}, message: ${err.message}`);
5806  } else {
5807    console.info(`SkipToQueueItem successfully`);
5808  }
5809});
5810
5811```
5812
5813### getOutputDevice<sup>10+</sup>
5814
5815getOutputDevice(): Promise\<OutputDeviceInfo>
5816
5817Obtains the output device information. This API uses a promise to return the result.
5818
5819**System capability**: SystemCapability.Multimedia.AVSession.Core
5820
5821**Return value**
5822
5823| Type                                              | Description                                      |
5824| ------------------------------------------------- | ------------------------------------------------ |
5825| Promise<[OutputDeviceInfo](#outputdeviceinfo10)\> | Promise used to return the information obtained. |
5826
5827**Error codes**
5828
5829For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5830
5831| ID      | Error Message                          |
5832| ------- | -------------------------------------- |
5833| 6600101 | Session service exception.             |
5834| 6600103 | The session controller does not exist. |
5835
5836**Example**
5837
5838```ts
5839import { BusinessError } from '@ohos.base';
5840
5841avsessionController.getOutputDevice().then((deviceInfo: avSession.OutputDeviceInfo) => {
5842  console.info(`GetOutputDevice : SUCCESS`);
5843}).catch((err: BusinessError) => {
5844  console.error(`GetOutputDevice BusinessError: code: ${err.code}, message: ${err.message}`);
5845});
5846
5847```
5848
5849### getOutputDevice<sup>10+</sup>
5850
5851getOutputDevice(callback: AsyncCallback\<OutputDeviceInfo>): void
5852
5853Obtains the output device information. This API uses an asynchronous callback to return the result.
5854
5855**System capability**: SystemCapability.Multimedia.AVSession.Core
5856
5857**Parameters**
5858
5859| Name     | Type                                                    | Mandatory | Description                                       |
5860| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------- |
5861| callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo10)\> | Yes       | Callback used to return the information obtained. |
5862
5863**Error codes**
5864
5865For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5866
5867| ID      | Error Message                          |
5868| ------- | -------------------------------------- |
5869| 6600101 | Session service exception.             |
5870| 6600103 | The session controller does not exist. |
5871
5872**Example**
5873
5874```ts
5875import { BusinessError } from '@ohos.base';
5876
5877avsessionController.getOutputDevice((err: BusinessError, deviceInfo: avSession.OutputDeviceInfo) => {
5878  if (err) {
5879    console.error(`GetOutputDevice BusinessError: code: ${err.code}, message: ${err.message}`);
5880  } else {
5881    console.info(`GetOutputDevice : SUCCESS`);
5882  }
5883});
5884
5885```
5886
5887### sendAVKeyEvent<sup>10+</sup>
5888
5889sendAVKeyEvent(event: KeyEvent): Promise\<void>
5890
5891Sends a key event to the session corresponding to this controller. This API uses a promise to return the result.
5892
5893**System capability**: SystemCapability.Multimedia.AVSession.Core
5894
5895**Parameters**
5896
5897| Name  | Type                            | Mandatory | Description |
5898| ----- | ------------------------------- | --------- | ----------- |
5899| event | [KeyEvent](js-apis-keyevent.md) | Yes       | Key event.  |
5900
5901**Error codes**
5902
5903For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5904
5905| ID      | Error Message                          |
5906| ------- | -------------------------------------- |
5907| 6600101 | Session service exception.             |
5908| 6600102 | The session does not exist.            |
5909| 6600103 | The session controller does not exist. |
5910| 6600105 | Invalid session command.               |
5911| 6600106 | The session is not activated.          |
5912
5913**Return value**
5914
5915| Type           | Description                                                  |
5916| -------------- | ------------------------------------------------------------ |
5917| Promise\<void> | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned. |
5918
5919**Example**
5920
5921```ts
5922import keyEvent from '@ohos.multimodalInput.keyEvent';
5923import { BusinessError } from '@ohos.base';
5924
5925let keyItem: keyEvent.Key = {code:0x49, pressedTime:2, deviceId:0};
5926let event: keyEvent.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};
5927
5928avsessionController.sendAVKeyEvent(event).then(() => {
5929  console.info(`SendAVKeyEvent Successfully`);
5930}).catch((err: BusinessError) => {
5931  console.error(`SendAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`);
5932});
5933
5934```
5935
5936### sendAVKeyEvent<sup>10+</sup>
5937
5938sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback\<void>): void
5939
5940Sends a key event to the session corresponding to this controller. This API uses an asynchronous callback to return the result.
5941
5942**System capability**: SystemCapability.Multimedia.AVSession.Core
5943
5944**Parameters**
5945
5946| Name     | Type                            | Mandatory | Description                                                  |
5947| -------- | ------------------------------- | --------- | ------------------------------------------------------------ |
5948| event    | [KeyEvent](js-apis-keyevent.md) | Yes       | Key event.                                                   |
5949| callback | AsyncCallback\<void>            | Yes       | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object. |
5950
5951**Error codes**
5952
5953For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5954
5955| ID      | Error Message                          |
5956| ------- | -------------------------------------- |
5957| 6600101 | Session service exception.             |
5958| 6600102 | The session does not exist.            |
5959| 6600103 | The session controller does not exist. |
5960| 6600105 | Invalid session command.               |
5961| 6600106 | The session is not activated.          |
5962
5963**Example**
5964
5965```ts
5966import keyEvent from '@ohos.multimodalInput.keyEvent';
5967import { BusinessError } from '@ohos.base';
5968
5969let keyItem: keyEvent.Key = {code:0x49, pressedTime:2, deviceId:0};
5970let event: keyEvent.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};
5971
5972avsessionController.sendAVKeyEvent(event, (err: BusinessError) => {
5973  if (err) {
5974    console.error(`SendAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`);
5975  } else {
5976    console.info(`SendAVKeyEvent Successfully`);
5977  }
5978});
5979
5980```
5981
5982### getLaunchAbility<sup>10+</sup>
5983
5984getLaunchAbility(): Promise\<WantAgent>
5985
5986Obtains the **WantAgent** object saved by the application in the session. This API uses a promise to return the result.
5987
5988**System capability**: SystemCapability.Multimedia.AVSession.Core
5989
5990**Return value**
5991
5992| Type                                                    | Description                                                  |
5993| ------------------------------------------------------- | ------------------------------------------------------------ |
5994| Promise<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Promise used to return the object saved by calling [setLaunchAbility](#setlaunchability10). The object includes the application attribute, such as the bundle name, ability name, and device ID. |
5995
5996**Error codes**
5997
5998For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
5999
6000| ID      | Error Message                          |
6001| ------- | -------------------------------------- |
6002| 6600101 | Session service exception.             |
6003| 6600102 | The session does not exist.            |
6004| 6600103 | The session controller does not exist. |
6005
6006**Example**
6007
6008```ts
6009import { BusinessError } from '@ohos.base';
6010
6011avsessionController.getLaunchAbility().then((agent: object) => {
6012  console.info(`GetLaunchAbility : SUCCESS : wantAgent : ${agent}`);
6013}).catch((err: BusinessError) => {
6014  console.error(`GetLaunchAbility BusinessError: code: ${err.code}, message: ${err.message}`);
6015});
6016
6017```
6018
6019### getLaunchAbility<sup>10+</sup>
6020
6021getLaunchAbility(callback: AsyncCallback\<WantAgent>): void
6022
6023Obtains the **WantAgent** object saved by the application in the session. This API uses an asynchronous callback to return the result.
6024
6025**System capability**: SystemCapability.Multimedia.AVSession.Core
6026
6027**Parameters**
6028
6029| Name     | Type                                                         | Mandatory | Description                                                  |
6030| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
6031| callback | AsyncCallback<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Yes       | Callback used to return the object saved by calling [setLaunchAbility](#setlaunchability10). The object includes the application attribute, such as the bundle name, ability name, and device ID. |
6032
6033**Error codes**
6034
6035For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6036
6037| ID      | Error Message                          |
6038| ------- | -------------------------------------- |
6039| 6600101 | Session service exception.             |
6040| 6600102 | The session does not exist.            |
6041| 6600103 | The session controller does not exist. |
6042
6043**Example**
6044
6045```ts
6046import { BusinessError } from '@ohos.base';
6047
6048avsessionController.getLaunchAbility((err: BusinessError, agent: object) => {
6049  if (err) {
6050    console.error(`GetLaunchAbility BusinessError: code: ${err.code}, message: ${err.message}`);
6051  } else {
6052    console.info(`GetLaunchAbility : SUCCESS : wantAgent : ${agent}`);
6053  }
6054});
6055
6056```
6057
6058### getRealPlaybackPositionSync<sup>10+</sup>
6059
6060getRealPlaybackPositionSync(): number
6061
6062Obtains the playback position.
6063
6064**System capability**: SystemCapability.Multimedia.AVSession.Core
6065
6066**Return value**
6067
6068| Type   | Description                         |
6069| ------ | ----------------------------------- |
6070| number | Playback position, in milliseconds. |
6071
6072**Error codes**
6073
6074For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6075
6076| ID      | Error Message                          |
6077| ------- | -------------------------------------- |
6078| 6600101 | Session service exception.             |
6079| 6600103 | The session controller does not exist. |
6080
6081**Example**
6082
6083```ts
6084let time: number = avsessionController.getRealPlaybackPositionSync();
6085
6086```
6087
6088### isActive<sup>10+</sup>
6089
6090isActive(): Promise\<boolean>
6091
6092Checks whether the session is activated. This API uses a promise to return the result.
6093
6094**System capability**: SystemCapability.Multimedia.AVSession.Core
6095
6096**Return value**
6097
6098| Type              | Description                                                  |
6099| ----------------- | ------------------------------------------------------------ |
6100| Promise<boolean\> | Promise used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned. |
6101
6102**Error codes**
6103
6104For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6105
6106| ID      | Error Message                          |
6107| ------- | -------------------------------------- |
6108| 6600101 | Session service exception.             |
6109| 6600102 | The session does not exist.            |
6110| 6600103 | The session controller does not exist. |
6111
6112**Example**
6113
6114```ts
6115import { BusinessError } from '@ohos.base';
6116
6117avsessionController.isActive().then((isActive: boolean) => {
6118  console.info(`IsActive : SUCCESS : isactive : ${isActive}`);
6119}).catch((err: BusinessError) => {
6120  console.error(`IsActive BusinessError: code: ${err.code}, message: ${err.message}`);
6121});
6122
6123```
6124
6125### isActive<sup>10+</sup>
6126
6127isActive(callback: AsyncCallback\<boolean>): void
6128
6129Checks whether the session is activated. This API uses an asynchronous callback to return the result.
6130
6131**System capability**: SystemCapability.Multimedia.AVSession.Core
6132
6133**Parameters**
6134
6135| Name     | Type                    | Mandatory | Description                                                  |
6136| -------- | ----------------------- | --------- | ------------------------------------------------------------ |
6137| callback | AsyncCallback<boolean\> | Yes       | Callback used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned. |
6138
6139**Error codes**
6140
6141For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6142
6143| ID      | Error Message                          |
6144| ------- | -------------------------------------- |
6145| 6600101 | Session service exception.             |
6146| 6600102 | The session does not exist.            |
6147| 6600103 | The session controller does not exist. |
6148
6149**Example**
6150
6151```ts
6152import { BusinessError } from '@ohos.base';
6153
6154avsessionController.isActive((err: BusinessError, isActive: boolean) => {
6155  if (err) {
6156    console.error(`IsActive BusinessError: code: ${err.code}, message: ${err.message}`);
6157  } else {
6158    console.info(`IsActive : SUCCESS : isactive : ${isActive}`);
6159  }
6160});
6161
6162```
6163
6164### destroy<sup>10+</sup>
6165
6166destroy(): Promise\<void>
6167
6168Destroys this controller. A controller can no longer be used after being destroyed. This API uses a promise to return the result.
6169
6170**System capability**: SystemCapability.Multimedia.AVSession.Core
6171
6172**Return value**
6173
6174| Type           | Description                                                  |
6175| -------------- | ------------------------------------------------------------ |
6176| Promise\<void> | Promise used to return the result. If the controller is destroyed, no value is returned; otherwise, an error object is returned. |
6177
6178**Error codes**
6179
6180For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6181
6182| ID      | Error Message                          |
6183| ------- | -------------------------------------- |
6184| 6600101 | Session service exception.             |
6185| 6600103 | The session controller does not exist. |
6186
6187**Example**
6188
6189```ts
6190import { BusinessError } from '@ohos.base';
6191
6192avsessionController.destroy().then(() => {
6193  console.info(`Destroy : SUCCESS `);
6194}).catch((err: BusinessError) => {
6195  console.error(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`);
6196});
6197
6198```
6199
6200### destroy<sup>10+</sup>
6201
6202destroy(callback: AsyncCallback\<void>): void
6203
6204Destroys this controller. A controller can no longer be used after being destroyed. This API uses an asynchronous callback to return the result.
6205
6206**System capability**: SystemCapability.Multimedia.AVSession.Core
6207
6208**Parameters**
6209
6210| Name     | Type                 | Mandatory | Description                                                  |
6211| -------- | -------------------- | --------- | ------------------------------------------------------------ |
6212| callback | AsyncCallback\<void> | Yes       | Callback used to return the result. If the controller is destroyed, **err** is **undefined**; otherwise, **err** is an error object. |
6213
6214**Error codes**
6215
6216For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6217
6218| ID      | Error Message                          |
6219| ------- | -------------------------------------- |
6220| 6600101 | Session service exception.             |
6221| 6600103 | The session controller does not exist. |
6222
6223**Example**
6224
6225```ts
6226import { BusinessError } from '@ohos.base';
6227
6228avsessionController.destroy((err: BusinessError) => {
6229  if (err) {
6230    console.error(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`);
6231  } else {
6232    console.info(`Destroy : SUCCESS `);
6233  }
6234});
6235
6236```
6237
6238### getValidCommands<sup>10+</sup>
6239
6240getValidCommands(): Promise\<Array\<AVControlCommandType>>
6241
6242Obtains valid commands supported by the session. This API uses a promise to return the result.
6243
6244**System capability**: SystemCapability.Multimedia.AVSession.Core
6245
6246**Return value**
6247
6248| Type                                                         | Description                                     |
6249| ------------------------------------------------------------ | ----------------------------------------------- |
6250| Promise<Array<[AVControlCommandType](#avcontrolcommandtype10)\>\> | Promise used to return a set of valid commands. |
6251
6252**Error codes**
6253
6254For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6255
6256| ID      | Error Message                          |
6257| ------- | -------------------------------------- |
6258| 6600101 | Session service exception.             |
6259| 6600102 | The session does not exist.            |
6260| 6600103 | The session controller does not exist. |
6261
6262**Example**
6263
6264```ts
6265import { BusinessError } from '@ohos.base';
6266
6267avsessionController.getValidCommands().then((validCommands: avSession.AVControlCommandType[]) => {
6268  console.info(`GetValidCommands : SUCCESS : size : ${validCommands.length}`);
6269}).catch((err: BusinessError) => {
6270  console.error(`GetValidCommands BusinessError: code: ${err.code}, message: ${err.message}`);
6271});
6272
6273```
6274
6275### getValidCommands<sup>10+</sup>
6276
6277getValidCommands(callback: AsyncCallback\<Array\<AVControlCommandType>>): void
6278
6279Obtains valid commands supported by the session. This API uses an asynchronous callback to return the result.
6280
6281**System capability**: SystemCapability.Multimedia.AVSession.Core
6282
6283**Parameters**
6284
6285| Name     | Type                                                         | Mandatory | Description                                      |
6286| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------ |
6287| callback | AsyncCallback\<Array\<[AVControlCommandType](#avcontrolcommandtype10)\>\> | Yes       | Callback used to return a set of valid commands. |
6288
6289**Error codes**
6290
6291For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6292
6293| ID      | Error Message                          |
6294| ------- | -------------------------------------- |
6295| 6600101 | Session service exception.             |
6296| 6600102 | The session does not exist.            |
6297| 6600103 | The session controller does not exist. |
6298
6299**Example**
6300
6301```ts
6302import { BusinessError } from '@ohos.base';
6303
6304avsessionController.getValidCommands((err: BusinessError, validCommands: avSession.AVControlCommandType[]) => {
6305  if (err) {
6306    console.error(`GetValidCommands BusinessError: code: ${err.code}, message: ${err.message}`);
6307  } else {
6308    console.info(`GetValidCommands : SUCCESS : size : ${validCommands.length}`);
6309  }
6310});
6311
6312```
6313
6314### sendControlCommand<sup>10+</sup>
6315
6316sendControlCommand(command: AVControlCommand): Promise\<void>
6317
6318Sends a control command to the session through the controller. This API uses a promise to return the result.
6319
6320> **NOTE**
6321>
6322> 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'](#onplay10), [on'pause'](#onpause10), and the like.
6323
6324**System capability**: SystemCapability.Multimedia.AVSession.Core
6325
6326**Parameters**
6327
6328| Name    | Type                                    | Mandatory | Description      |
6329| ------- | --------------------------------------- | --------- | ---------------- |
6330| command | [AVControlCommand](#avcontrolcommand10) | Yes       | Command to send. |
6331
6332**Return value**
6333
6334| Type           | Description                                                  |
6335| -------------- | ------------------------------------------------------------ |
6336| Promise\<void> | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned. |
6337
6338**Error codes**
6339
6340For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6341
6342| ID      | Error Message                          |
6343| ------- | -------------------------------------- |
6344| 6600101 | Session service exception.             |
6345| 6600102 | The session does not exist.            |
6346| 6600103 | The session controller does not exist. |
6347| 6600105 | Invalid session command.               |
6348| 6600106 | The session is not activated.          |
6349| 6600107 | Too many commands or events.           |
6350
6351**Example**
6352
6353```ts
6354import avSession from '@ohos.multimedia.avsession';
6355import { BusinessError } from '@ohos.base';
6356
6357let avCommand: avSession.AVControlCommand = {command:'play'};
6358avsessionController.sendControlCommand(avCommand).then(() => {
6359  console.info(`SendControlCommand successfully`);
6360}).catch((err: BusinessError) => {
6361  console.error(`SendControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
6362});
6363
6364```
6365
6366### sendControlCommand<sup>10+</sup>
6367
6368sendControlCommand(command: AVControlCommand, callback: AsyncCallback\<void>): void
6369
6370Sends a control command to the session through the controller. This API uses an asynchronous callback to return the result.
6371
6372> **NOTE**
6373>
6374> 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'](#onplay10), [on'pause'](#onpause10), and the like.
6375
6376**System capability**: SystemCapability.Multimedia.AVSession.Core
6377
6378**Parameters**
6379
6380| Name     | Type                                    | Mandatory | Description                                                  |
6381| -------- | --------------------------------------- | --------- | ------------------------------------------------------------ |
6382| command  | [AVControlCommand](#avcontrolcommand10) | Yes       | Command to send.                                             |
6383| callback | AsyncCallback\<void>                    | Yes       | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. |
6384
6385**Error codes**
6386
6387For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6388
6389| ID      | Error Message                          |
6390| ------- | -------------------------------------- |
6391| 6600101 | Session service exception.             |
6392| 6600102 | The session does not exist.            |
6393| 6600103 | The session controller does not exist. |
6394| 6600105 | Invalid session command.               |
6395| 6600106 | The session is not activated.          |
6396| 6600107 | Too many commands or events.           |
6397
6398**Example**
6399
6400```ts
6401import avSession from '@ohos.multimedia.avsession';
6402import { BusinessError } from '@ohos.base';
6403
6404let avCommand: avSession.AVControlCommand = {command:'play'};
6405avsessionController.sendControlCommand(avCommand, (err: BusinessError) => {
6406  if (err) {
6407    console.error(`SendControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
6408  } else {
6409    console.info(`SendControlCommand successfully`);
6410  }
6411});
6412
6413```
6414
6415### sendCommonCommand<sup>10+</sup>
6416
6417sendCommonCommand(command: string, args: {[key: string]: Object}): Promise\<void>
6418
6419Sends a custom control command to the session through the controller. This API uses a promise to return the result.
6420
6421**System capability**: SystemCapability.Multimedia.AVSession.Core
6422
6423**Parameters**
6424
6425| Name    | Type                    | Mandatory | Description                                                  |
6426| ------- | ----------------------- | --------- | ------------------------------------------------------------ |
6427| command | string                  | Yes       | Name of the custom control command.                          |
6428| args | {[key: string]: any} | Yes       | Parameters in key-value pair format carried in the custom control command. |
6429
6430> **NOTE**
6431> The **args** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want (Want)](./js-apis-app-ability-want.md).
6432
6433**Return value**
6434
6435| Type           | Description                                                  |
6436| -------------- | ------------------------------------------------------------ |
6437| Promise\<void> | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned. |
6438
6439**Error codes**
6440
6441For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6442
6443| ID      | Error Message                          |
6444| ------- | -------------------------------------- |
6445| 6600101 | Session service exception.             |
6446| 6600102 | The session does not exist.            |
6447| 6600103 | The session controller does not exist. |
6448| 6600105 | Invalid session command.               |
6449| 6600106 | The session is not activated.          |
6450| 6600107 | Too many commands or events.           |
6451
6452**Example**
6453
6454```ts
6455import avSession from '@ohos.multimedia.avsession';
6456import { BusinessError } from '@ohos.base';
6457
6458let avSessionController: avSession.AVSessionController | undefined = undefined;
6459let currentAVSession: avSession.AVSession | undefined = undefined;
6460let tag = "createNewSession";
6461let context: Context = getContext(this);
6462let sessionId: string = "";
6463avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
6464  if (err) {
6465    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
6466  } else {
6467    currentAVSession = data;
6468  }
6469});
6470if (currentAVSession !== undefined) {
6471  sessionId = (currentAVSession as avSession.AVSession).sessionId;
6472  avSession.createController(sessionId).then((controller: avSession.AVSessionController) => {
6473    avSessionController = controller;
6474  }).catch((err: BusinessError) => {
6475    console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
6476  });
6477}
6478
6479let commandName = "my_command";
6480if (avSessionController !== undefined) {
6481  (avSessionController as avSession.AVSessionController).sendCommonCommand(commandName, {command : "This is my command"}).then(() => {
6482    console.info(`SendCommonCommand successfully`);
6483  }).catch((err: BusinessError) => {
6484    console.error(`SendCommonCommand BusinessError: code: ${err.code}, message: ${err.message}`);
6485  })
6486}
6487
6488```
6489
6490### sendCommonCommand<sup>10+</sup>
6491
6492sendCommonCommand(command: string, args: {[key: string]: Object}, callback: AsyncCallback\<void>): void
6493
6494Sends a custom control command to the session through the controller. This API uses an asynchronous callback to return the result.
6495
6496**System capability**: SystemCapability.Multimedia.AVSession.Core
6497
6498**Parameters**
6499
6500| Name     | Type                    | Mandatory | Description                                                  |
6501| -------- | ----------------------- | --------- | ------------------------------------------------------------ |
6502| command  | string                  | Yes       | Name of the custom control command.                          |
6503| args | {[key: string]: any} | Yes       | Parameters in key-value pair format carried in the custom control command. |
6504| callback | AsyncCallback\<void>    | Yes       | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. |
6505
6506> **NOTE**
6507> The **args** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want (Want)](./js-apis-app-ability-want.md).
6508
6509**Error codes**
6510
6511For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6512
6513| ID      | Error Message                          |
6514| ------- | -------------------------------------- |
6515| 6600101 | Session service exception.             |
6516| 6600102 | The session does not exist.            |
6517| 6600103 | The session controller does not exist. |
6518| 6600105 | Invalid session command.               |
6519| 6600106 | The session is not activated.          |
6520| 6600107 | Too many commands or events.           |
6521
6522**Example**
6523
6524```ts
6525import avSession from '@ohos.multimedia.avsession';
6526import { BusinessError } from '@ohos.base';
6527let avSessionController: avSession.AVSessionController | undefined = undefined;
6528let currentAVSession: avSession.AVSession | undefined = undefined;
6529let tag = "createNewSession";
6530let context: Context = getContext(this);
6531
6532avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
6533  if (err) {
6534    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
6535  } else {
6536    currentAVSession = data;
6537  }
6538});
6539if (currentAVSession !== undefined) {
6540  avSession.createController((currentAVSession as avSession.AVSession).sessionId).then((controller: avSession.AVSessionController) => {
6541    avSessionController = controller;
6542  }).catch((err: BusinessError) => {
6543    console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
6544  });
6545}
6546
6547let commandName = "my_command";
6548if (avSessionController !== undefined) {
6549  (avSessionController as avSession.AVSessionController).sendCommonCommand(commandName, {command : "This is my command"}, (err: BusinessError) => {
6550    if (err) {
6551        console.error(`SendCommonCommand BusinessError: code: ${err.code}, message: ${err.message}`);
6552    }
6553  })
6554}
6555
6556```
6557
6558### getExtras<sup>10+</sup>
6559
6560getExtras(): Promise\<{[key: string]: Object}>
6561
6562Obtains the custom media packet set by the provider. This API uses a promise to return the result.
6563
6564**System capability**: SystemCapability.Multimedia.AVSession.Core
6565
6566**Return value**
6567
6568| Type                              | Description                                                  |
6569| --------------------------------- | ------------------------------------------------------------ |
6570| 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**. |
6571
6572**Error codes**
6573
6574For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6575
6576| ID      | Error Message                          |
6577| ------- | -------------------------------------- |
6578| 6600101 | Session service exception.             |
6579| 6600102 | The session does not exist.            |
6580| 6600103 | The session controller does not exist. |
6581| 6600105 | Invalid session command.               |
6582| 6600107 | Too many commands or events.           |
6583
6584**Example**
6585
6586```ts
6587import avSession from '@ohos.multimedia.avsession';
6588import { BusinessError } from '@ohos.base';
6589
6590let avSessionController: avSession.AVSessionController | undefined = undefined;
6591let currentAVSession: avSession.AVSession | undefined = undefined;
6592let tag = "createNewSession";
6593let context: Context = getContext(this);
6594
6595avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
6596  if (err) {
6597    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
6598  } else {
6599    currentAVSession = data;
6600  }
6601});
6602if (currentAVSession !== undefined) {
6603  avSession.createController((currentAVSession as avSession.AVSession).sessionId).then((controller: avSession.AVSessionController) => {
6604    avSessionController = controller;
6605  }).catch((err: BusinessError) => {
6606    console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
6607  });
6608}
6609
6610if (avSessionController !== undefined) {
6611  (avSessionController as avSession.AVSessionController).getExtras().then((extras) => {
6612    console.info(`getExtras : SUCCESS : ${extras}`);
6613  }).catch((err: BusinessError) => {
6614    console.error(`getExtras BusinessError: code: ${err.code}, message: ${err.message}`);
6615  });
6616}
6617
6618```
6619
6620### getExtras<sup>10+</sup>
6621
6622getExtras(callback: AsyncCallback\<{[key: string]: Object}>): void
6623
6624Obtains the custom media packet set by the provider. This API uses an asynchronous callback to return the result.
6625
6626**System capability**: SystemCapability.Multimedia.AVSession.Core
6627
6628**Parameters**
6629
6630| Name     | Type                                    | Mandatory | Description                                                  |
6631| -------- | --------------------------------------- | --------- | ------------------------------------------------------------ |
6632| 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**. |
6633
6634**Error codes**
6635
6636For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6637
6638| ID      | Error Message                          |
6639| ------- | -------------------------------------- |
6640| 6600101 | Session service exception.             |
6641| 6600102 | The session does not exist.            |
6642| 6600103 | The session controller does not exist. |
6643| 6600105 | Invalid session command.               |
6644| 6600107 | Too many commands or events.           |
6645
6646**Example**
6647
6648```ts
6649import avSession from '@ohos.multimedia.avsession';
6650import { BusinessError } from '@ohos.base';
6651
6652let avSessionController: avSession.AVSessionController | undefined = undefined;
6653let currentAVSession: avSession.AVSession | undefined = undefined;
6654let tag = "createNewSession";
6655let context: Context = getContext(this);
6656
6657avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
6658  if (err) {
6659    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
6660  } else {
6661    currentAVSession = data;
6662  }
6663});
6664if (currentAVSession !== undefined) {
6665  avSession.createController((currentAVSession as avSession.AVSession).sessionId).then((controller: avSession.AVSessionController) => {
6666    avSessionController = controller;
6667  }).catch((err: BusinessError) => {
6668    console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
6669  });
6670}
6671
6672if (avSessionController !== undefined) {
6673  (avSessionController as avSession.AVSessionController).getExtras((err, extras) => {
6674    if (err) {
6675      console.error(`getExtras BusinessError: code: ${err.code}, message: ${err.message}`);
6676    } else {
6677      console.info(`getExtras : SUCCESS : ${extras}`);
6678    }
6679  });
6680}
6681
6682```
6683
6684### on('metadataChange')<sup>10+</sup>
6685
6686on(type: 'metadataChange', filter: Array\<keyof AVMetadata> | 'all', callback: (data: AVMetadata) => void)
6687
6688Subscribes to metadata change events.
6689
6690**System capability**: SystemCapability.Multimedia.AVSession.Core
6691
6692**Parameters**
6693
6694| Name     | Type                                                         | Mandatory | Description                                                  |
6695| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
6696| type     | string                                                       | Yes       | Event type. The event **'metadataChange'** is triggered when the session metadata changes. |
6697| filter   | Array\<keyof&nbsp;[AVMetadata](#avmetadata10)\>&nbsp;&#124;&nbsp;'all' | Yes       | The value **'all'** indicates that any metadata field change will trigger the event, and **Array<keyof&nbsp;[AVMetadata](#avmetadata10)\>** indicates that only changes to the listed metadata field will trigger the event. |
6698| callback | (data: [AVMetadata](#avmetadata10)) => void                  | Yes       | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata. |
6699
6700**Error codes**
6701
6702For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6703
6704| ID      | Error Message                          |
6705| ------- | -------------------------------------- |
6706| 6600101 | Session service exception.             |
6707| 6600103 | The session controller does not exist. |
6708
6709**Example**
6710
6711```ts
6712avsessionController.on('metadataChange', 'all', (metadata: avSession.AVMetadata) => {
6713  console.info(`on metadataChange assetId : ${metadata.assetId}`);
6714});
6715
6716avsessionController.on('metadataChange', ['assetId', 'title', 'description'], (metadata: avSession.AVMetadata) => {
6717  console.info(`on metadataChange assetId : ${metadata.assetId}`);
6718});
6719
6720
6721```
6722
6723### off('metadataChange')<sup>10+</sup>
6724
6725off(type: 'metadataChange', callback?: (data: AVMetadata) => void)
6726
6727Unsubscribes from metadata change events. This API is called by the controller.
6728
6729**System capability**: SystemCapability.Multimedia.AVSession.Core
6730
6731**Parameters**
6732
6733| Name     | Type                                        | Mandatory | Description                                                  |
6734| -------- | ------------------------------------------- | --------- | ------------------------------------------------------------ |
6735| type     | string                                      | Yes       | Event type, which is **'metadataChange'** in this case.      |
6736| callback | (data: [AVMetadata](#avmetadata10)) => void | No        | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. |
6737
6738**Error codes**
6739
6740For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6741
6742| ID      | Error Message                          |
6743| ------- | -------------------------------------- |
6744| 6600101 | Session service exception.             |
6745| 6600103 | The session controller does not exist. |
6746
6747**Example**
6748
6749```ts
6750avsessionController.off('metadataChange');
6751
6752```
6753
6754### on('playbackStateChange')<sup>10+</sup>
6755
6756on(type: 'playbackStateChange', filter: Array\<keyof AVPlaybackState> | 'all', callback: (state: AVPlaybackState) => void)
6757
6758Subscribes to playback state change events.
6759
6760**System capability**: SystemCapability.Multimedia.AVSession.Core
6761
6762**Parameters**
6763
6764| Name     | Type                                                         | Mandatory | Description                                                  |
6765| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
6766| type     | string                                                       | Yes       | Event type. The event **'playbackStateChange'** is triggered when the playback state changes. |
6767| filter   | Array\<keyof&nbsp;[AVPlaybackState](#avplaybackstate10)\>&nbsp;&#124;&nbsp;'all' | Yes       | The value **'all'** indicates that any playback state field change will trigger the event, and **Array<keyof&nbsp;[AVPlaybackState](#avplaybackstate10)\>** indicates that only changes to the listed playback state field will trigger the event. |
6768| callback | (state: [AVPlaybackState](#avplaybackstate10)) => void       | Yes       | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state. |
6769
6770**Error codes**
6771
6772For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6773
6774| ID      | Error Message                          |
6775| ------- | -------------------------------------- |
6776| 6600101 | Session service exception.             |
6777| 6600103 | The session controller does not exist. |
6778
6779**Example**
6780
6781```ts
6782avsessionController.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
6783  console.info(`on playbackStateChange state : ${playbackState.state}`);
6784});
6785
6786avsessionController.on('playbackStateChange', ['state', 'speed', 'loopMode'], (playbackState: avSession.AVPlaybackState) => {
6787  console.info(`on playbackStateChange state : ${playbackState.state}`);
6788});
6789
6790```
6791
6792### off('playbackStateChange')<sup>10+</sup>
6793
6794off(type: 'playbackStateChange', callback?: (state: AVPlaybackState) => void)
6795
6796Unsubscribes from playback state change events. This API is called by the controller.
6797
6798**System capability**: SystemCapability.Multimedia.AVSession.Core
6799
6800**Parameters**
6801
6802| Name     | Type                                                   | Mandatory | Description                                                  |
6803| -------- | ------------------------------------------------------ | --------- | ------------------------------------------------------------ |
6804| type     | string                                                 | Yes       | Event type, which is **'playbackStateChange'** in this case. |
6805| callback | (state: [AVPlaybackState](#avplaybackstate10)) => void | No        | Callback used for unsubscription. The **state** parameter in the callback indicates the changed playback state.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. |
6806
6807**Error codes**
6808
6809For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6810
6811| ID      | Error Message                          |
6812| ------- | -------------------------------------- |
6813| 6600101 | Session service exception.             |
6814| 6600103 | The session controller does not exist. |
6815
6816**Example**
6817
6818```ts
6819avsessionController.off('playbackStateChange');
6820```
6821
6822### on('sessionDestroy')<sup>10+</sup>
6823
6824on(type: 'sessionDestroy', callback: () => void)
6825
6826Subscribes to session destruction events.
6827
6828**System capability**: SystemCapability.Multimedia.AVSession.Core
6829
6830**Parameters**
6831
6832| Name     | Type       | Mandatory | Description                                                  |
6833| -------- | ---------- | --------- | ------------------------------------------------------------ |
6834| type     | string     | Yes       | Event type. The event **'sessionDestroy'** is triggered when a session is destroyed. |
6835| callback | () => void | Yes       | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. |
6836
6837**Error codes**
6838
6839For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6840
6841| ID      | Error Message                          |
6842| ------- | -------------------------------------- |
6843| 6600101 | Session service exception.             |
6844| 6600103 | The session controller does not exist. |
6845
6846**Example**
6847
6848```ts
6849avsessionController.on('sessionDestroy', () => {
6850  console.info(`on sessionDestroy : SUCCESS `);
6851});
6852
6853```
6854
6855### off('sessionDestroy')<sup>10+</sup>
6856
6857off(type: 'sessionDestroy', callback?: () => void)
6858
6859Unsubscribes from session destruction events. This API is called by the controller.
6860
6861**System capability**: SystemCapability.Multimedia.AVSession.Core
6862
6863**Parameters**
6864
6865| Name     | Type       | Mandatory | Description                                                  |
6866| -------- | ---------- | --------- | ------------------------------------------------------------ |
6867| type     | string     | Yes       | Event type, which is **'sessionDestroy'** in this case.      |
6868| callback | () => void | No        | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. |
6869
6870**Error codes**
6871
6872For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6873
6874| ID      | Error Message                          |
6875| ------- | -------------------------------------- |
6876| 6600101 | Session service exception.             |
6877| 6600103 | The session controller does not exist. |
6878
6879**Example**
6880
6881```ts
6882avsessionController.off('sessionDestroy');
6883
6884```
6885
6886### on('activeStateChange')<sup>10+</sup>
6887
6888on(type: 'activeStateChange', callback: (isActive: boolean) => void)
6889
6890Subscribes to session activation state change events.
6891
6892**System capability**: SystemCapability.Multimedia.AVSession.Core
6893
6894**Parameters**
6895
6896| Name     | Type                        | Mandatory | Description                                                  |
6897| -------- | --------------------------- | --------- | ------------------------------------------------------------ |
6898| type     | string                      | Yes       | Event type. The event **'activeStateChange'** is triggered when the activation state of the session changes. |
6899| callback | (isActive: boolean) => void | Yes       | Callback used for subscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the service is activated, and **false** means the opposite. |
6900
6901**Error codes**
6902
6903For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6904
6905| ID      | Error Message                          |
6906| ------- | -------------------------------------- |
6907| 6600101 | Session service exception.             |
6908| 6600103 | The session controller does not exist. |
6909
6910**Example**
6911
6912```ts
6913avsessionController.on('activeStateChange', (isActive: boolean) => {
6914  console.info(`on activeStateChange : SUCCESS : isActive ${isActive}`);
6915});
6916
6917```
6918
6919### off('activeStateChange')<sup>10+</sup>
6920
6921off(type: 'activeStateChange', callback?: (isActive: boolean) => void)
6922
6923Unsubscribes from session activation state change events. This API is called by the controller.
6924
6925**System capability**: SystemCapability.Multimedia.AVSession.Core
6926
6927**Parameters**
6928
6929| Name     | Type                        | Mandatory | Description                                                  |
6930| -------- | --------------------------- | --------- | ------------------------------------------------------------ |
6931| type     | string                      | Yes       | Event type, which is **'activeStateChange'** in this case.   |
6932| callback | (isActive: boolean) => void | No        | Callback used for unsubscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the session is activated, and **false** means the opposite.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. |
6933
6934**Error codes**
6935
6936For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6937
6938| ID      | Error Message                          |
6939| ------- | -------------------------------------- |
6940| 6600101 | Session service exception.             |
6941| 6600103 | The session controller does not exist. |
6942
6943**Example**
6944
6945```ts
6946avsessionController.off('activeStateChange');
6947
6948```
6949
6950### on('validCommandChange')<sup>10+</sup>
6951
6952on(type: 'validCommandChange', callback: (commands: Array\<AVControlCommandType>) => void)
6953
6954Subscribes to valid command change events.
6955
6956**System capability**: SystemCapability.Multimedia.AVSession.Core
6957
6958**Parameters**
6959
6960| Name     | Type                                                         | Mandatory | Description                                                  |
6961| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
6962| type     | string                                                       | Yes       | Event type. The event **'validCommandChange'** is triggered when the valid commands supported by the session changes. |
6963| callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype10)\>) => void | Yes       | Callback used for subscription. The **commands** parameter in the callback is a set of valid commands. |
6964
6965**Error codes**
6966
6967For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
6968
6969| ID      | Error Message                          |
6970| ------- | -------------------------------------- |
6971| 6600101 | Session service exception.             |
6972| 6600103 | The session controller does not exist. |
6973
6974**Example**
6975
6976```ts
6977avsessionController.on('validCommandChange', (validCommands: avSession.AVControlCommandType[]) => {
6978  console.info(`validCommandChange : SUCCESS : size : ${validCommands.length}`);
6979  console.info(`validCommandChange : SUCCESS : validCommands : ${validCommands.values()}`);
6980});
6981
6982```
6983
6984### off('validCommandChange')<sup>10+</sup>
6985
6986off(type: 'validCommandChange', callback?: (commands: Array\<AVControlCommandType>) => void)
6987
6988Unsubscribes from valid command change events. This API is called by the controller.
6989
6990**System capability**: SystemCapability.Multimedia.AVSession.Core
6991
6992**Parameters**
6993
6994| Name     | Type                                                         | Mandatory | Description                                                  |
6995| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
6996| type     | string                                                       | Yes       | Event type, which is **'validCommandChange'** in this case.  |
6997| callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype10)\>) => void | No        | Callback used for unsubscription. The **commands** parameter in the callback is a set of valid commands.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. |
6998
6999**Error codes**
7000
7001For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
7002
7003| ID      | Error Message                          |
7004| ------- | -------------------------------------- |
7005| 6600101 | Session service exception.             |
7006| 6600103 | The session controller does not exist. |
7007
7008**Example**
7009
7010```ts
7011avsessionController.off('validCommandChange');
7012
7013```
7014
7015### on('outputDeviceChange')<sup>10+</sup>
7016
7017on(type: 'outputDeviceChange', callback: (state: ConnectionState, device: OutputDeviceInfo) => void): void
7018
7019Subscribes to output device change events.
7020
7021**System capability**: SystemCapability.Multimedia.AVSession.Core
7022
7023**Parameters**
7024
7025| Name     | Type                                                         | Mandatory | Description                                                  |
7026| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
7027| type     | string                                                       | Yes       | Event type. The event **'outputDeviceChange'** is triggered when the output device changes. |
7028| callback | (state: [ConnectionState](#connectionstate10), device: [OutputDeviceInfo](#outputdeviceinfo10)) => void | Yes       | Callback used for subscription. The **device** parameter in the callback indicates the output device information. |
7029
7030**Error codes**
7031
7032For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
7033
7034| ID      | Error Message                          |
7035| ------- | -------------------------------------- |
7036| 6600101 | Session service exception.             |
7037| 6600103 | The session controller does not exist. |
7038
7039**Example**
7040
7041```ts
7042avsessionController.on('outputDeviceChange', (state: avSession.ConnectionState, device: avSession.OutputDeviceInfo) => {
7043  console.info(`on outputDeviceChange state: ${state}, device : ${device}`);
7044});
7045
7046```
7047
7048### off('outputDeviceChange')<sup>10+</sup>
7049
7050off(type: 'outputDeviceChange', callback?: (state: ConnectionState, device: OutputDeviceInfo) => void): void
7051
7052Unsubscribes from output device change events. This API is called by the controller.
7053
7054**System capability**: SystemCapability.Multimedia.AVSession.Core
7055
7056**Parameters**
7057
7058| Name     | Type                                                         | Mandatory | Description                                                  |
7059| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
7060| type     | string                                                       | Yes       | Event type, which is **'outputDeviceChange'** in this case.  |
7061| callback | (state: [ConnectionState](#connectionstate10), device: [OutputDeviceInfo](#outputdeviceinfo10)) => void | No        | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. |
7062
7063**Error codes**
7064
7065For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
7066
7067| ID      | Error Message                          |
7068| ------- | -------------------------------------- |
7069| 6600101 | Session service exception.             |
7070| 6600103 | The session controller does not exist. |
7071
7072**Example**
7073
7074```ts
7075avsessionController.off('outputDeviceChange');
7076
7077```
7078
7079### on('sessionEvent')<sup>10+</sup>
7080
7081on(type: 'sessionEvent', callback: (sessionEvent: string, args: {[key:string]: Object}) => void): void
7082
7083Subscribes to session event change events. This API is called by the controller.
7084
7085**System capability**: SystemCapability.Multimedia.AVSession.Core
7086
7087**Parameters**
7088
7089| Name     | Type                                                         | Mandatory | Description                                                  |
7090| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
7091| type     | string                                                       | Yes       | Event type. The event **'sessionEvent'** is triggered when the session event changes. |
7092| 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. |
7093
7094**Error codes**
7095
7096For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
7097
7098| ID      | Error Message                          |
7099| ------- | -------------------------------------- |
7100| 6600101 | Session service exception.             |
7101| 6600103 | The session controller does not exist. |
7102
7103**Example**
7104
7105```ts
7106import avSession from '@ohos.multimedia.avsession';
7107import { BusinessError } from '@ohos.base';
7108
7109let avSessionController: avSession.AVSessionController | undefined = undefined;
7110let currentAVSession: avSession.AVSession | undefined = undefined;
7111let tag = "createNewSession";
7112let context: Context = getContext(this);
7113
7114avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
7115  if (err) {
7116    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
7117  } else {
7118    currentAVSession = data;
7119  }
7120});
7121if (currentAVSession !== undefined) {
7122  avSession.createController((currentAVSession as avSession.AVSession).sessionId).then((controller: avSession.AVSessionController) => {
7123    avSessionController = controller;
7124  }).catch((err: BusinessError) => {
7125    console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
7126  });
7127}
7128
7129if (avSessionController !== undefined) {
7130  (avSessionController as avSession.AVSessionController).on('sessionEvent', (sessionEvent, args) => {
7131    console.info(`OnSessionEvent, sessionEvent is ${sessionEvent}, args: ${JSON.stringify(args)}`);
7132  });
7133}
7134
7135```
7136
7137### off('sessionEvent')<sup>10+</sup>
7138
7139off(type: 'sessionEvent', callback?: (sessionEvent: string, args: {[key:string]: Object}) => void): void
7140
7141Unsubscribes from session event change events. This API is called by the controller.
7142
7143**System capability**: SystemCapability.Multimedia.AVSession.Core
7144
7145**Parameters**
7146
7147| Name     | Type                                                         | Mandatory | Description                                                  |
7148| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
7149| type     | string                                                       | Yes       | Event type, which is **'sessionEvent'** in this case.        |
7150| 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.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. |
7151
7152**Error codes**
7153
7154For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
7155
7156| ID      | Error Message                          |
7157| ------- | -------------------------------------- |
7158| 6600101 | Session service exception.             |
7159| 6600103 | The session controller does not exist. |
7160
7161**Example**
7162
7163```ts
7164avsessionController.off('sessionEvent');
7165
7166```
7167
7168### on('queueItemsChange')<sup>10+</sup>
7169
7170on(type: 'queueItemsChange', callback: (items: Array<[AVQueueItem](#avqueueitem10)\>) => void): void
7171
7172Subscribes to playlist item change events. This API is called by the controller.
7173
7174**System capability**: SystemCapability.Multimedia.AVSession.Core
7175
7176**Parameters**
7177
7178| Name     | Type                                                   | Mandatory | Description                                                  |
7179| -------- | ------------------------------------------------------ | --------- | ------------------------------------------------------------ |
7180| type     | string                                                 | Yes       | Event type. The event **'queueItemsChange'** is triggered when one or more items in the playlist changes. |
7181| callback | (items: Array<[AVQueueItem](#avqueueitem10)\>) => void | Yes       | Callback used for subscription. The **items** parameter in the callback indicates the changed items in the playlist. |
7182
7183**Error codes**
7184
7185For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
7186
7187| ID      | Error Message                          |
7188| ------- | -------------------------------------- |
7189| 6600101 | Session service exception.             |
7190| 6600103 | The session controller does not exist. |
7191
7192**Example**
7193
7194```ts
7195avsessionController.on('queueItemsChange', (items: avSession.AVQueueItem[]) => {
7196  console.info(`OnQueueItemsChange, items length is ${items.length}`);
7197});
7198
7199```
7200
7201### off('queueItemsChange')<sup>10+</sup>
7202
7203off(type: 'queueItemsChange', callback?: (items: Array<[AVQueueItem](#avqueueitem10)\>) => void): void
7204
7205Unsubscribes from playback item change events. This API is called by the controller.
7206
7207**System capability**: SystemCapability.Multimedia.AVSession.Core
7208
7209**Parameters**
7210
7211| Name     | Type                                                   | Mandatory | Description                                                  |
7212| -------- | ------------------------------------------------------ | --------- | ------------------------------------------------------------ |
7213| type     | string                                                 | Yes       | Event type, which is **'queueItemsChange'** in this case.    |
7214| callback | (items: Array<[AVQueueItem](#avqueueitem10)\>) => void | No        | Callback used for unsubscription. The **items** parameter in the callback indicates the changed items in the playlist.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. |
7215
7216**Error codes**
7217
7218For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
7219
7220| ID      | Error Message                          |
7221| ------- | -------------------------------------- |
7222| 6600101 | Session service exception.             |
7223| 6600103 | The session controller does not exist. |
7224
7225**Example**
7226
7227```ts
7228avsessionController.off('queueItemsChange');
7229
7230```
7231
7232### on('queueTitleChange')<sup>10+</sup>
7233
7234on(type: 'queueTitleChange', callback: (title: string) => void): void
7235
7236Subscribes to playlist name change events. This API is called by the controller.
7237
7238**System capability**: SystemCapability.Multimedia.AVSession.Core
7239
7240**Parameters**
7241
7242| Name     | Type                    | Mandatory | Description                                                  |
7243| -------- | ----------------------- | --------- | ------------------------------------------------------------ |
7244| type     | string                  | Yes       | Event type. The event **'queueTitleChange'** is triggered when the playlist name changes. |
7245| callback | (title: string) => void | Yes       | Callback used for subscription. The **title** parameter in the callback indicates the changed playlist name. |
7246
7247**Error codes**
7248
7249For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
7250
7251| ID      | Error Message                          |
7252| ------- | -------------------------------------- |
7253| 6600101 | Session service exception.             |
7254| 6600103 | The session controller does not exist. |
7255
7256**Example**
7257
7258```ts
7259avsessionController.on('queueTitleChange', (title: string) => {
7260  console.info(`queueTitleChange, title is ${title}`);
7261});
7262
7263```
7264
7265### off('queueTitleChange')<sup>10+</sup>
7266
7267off(type: 'queueTitleChange', callback?: (title: string) => void): void
7268
7269Unsubscribes from playlist name change events. This API is called by the controller.
7270
7271**System capability**: SystemCapability.Multimedia.AVSession.Core
7272
7273**Parameters**
7274
7275| Name     | Type                    | Mandatory | Description                                                  |
7276| -------- | ----------------------- | --------- | ------------------------------------------------------------ |
7277| type     | string                  | Yes       | Event type, which is **'queueTitleChange'** in this case.    |
7278| callback | (title: string) => void | No        | Callback used for unsubscription. The **items** parameter in the callback indicates the changed playlist name.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. |
7279
7280**Error codes**
7281
7282For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
7283
7284| ID      | Error Message                          |
7285| ------- | -------------------------------------- |
7286| 6600101 | Session service exception.             |
7287| 6600103 | The session controller does not exist. |
7288
7289**Example**
7290
7291```ts
7292avsessionController.off('queueTitleChange');
7293
7294```
7295
7296### on('extrasChange')<sup>10+</sup>
7297
7298on(type: 'extrasChange', callback: (extras: {[key:string]: Object}) => void): void
7299
7300Subscribes to custom media packet change events. This API is called by the controller.
7301
7302**System capability**: SystemCapability.Multimedia.AVSession.Core
7303
7304**Parameters**
7305
7306| Name     | Type                                     | Mandatory | Description                                                  |
7307| -------- | ---------------------------------------- | --------- | ------------------------------------------------------------ |
7308| type     | string                                   | Yes       | Event type. The event **'extrasChange'** is triggered when the provider sets a custom media packet. |
7309| 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**. |
7310
7311**Error codes**
7312
7313For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
7314
7315| ID      | Error Message                          |
7316| ------- | -------------------------------------- |
7317| 6600101 | Session service exception.             |
7318| 6600103 | The session controller does not exist. |
7319
7320**Example**
7321
7322```ts
7323import avSession from '@ohos.multimedia.avsession';
7324import { BusinessError } from '@ohos.base';
7325
7326let avSessionController: avSession.AVSessionController | undefined = undefined;
7327let currentAVSession: avSession.AVSession | undefined = undefined;
7328let tag = "createNewSession";
7329let context: Context = getContext(this);
7330
7331avSession.createAVSession(context, tag, "audio", (err: BusinessError, data: avSession.AVSession) => {
7332  if (err) {
7333    console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
7334  } else {
7335    currentAVSession = data;
7336  }
7337});
7338if (currentAVSession !== undefined) {
7339  avSession.createController((currentAVSession as avSession.AVSession).sessionId).then((controller: avSession.AVSessionController) => {
7340    avSessionController = controller;
7341  }).catch((err: BusinessError) => {
7342    console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
7343  });
7344}
7345
7346if (avSessionController !== undefined) {
7347  (avSessionController as avSession.AVSessionController).on('extrasChange', (extras) => {
7348    console.info(`Caught extrasChange event,the new extra is: ${JSON.stringify(extras)}`);
7349  });
7350}
7351
7352```
7353
7354### off('extrasChange')<sup>10+</sup>
7355
7356off(type: 'extrasChange', callback?: (extras: {[key:string]: Object}) => void): void
7357
7358Unsubscribes from custom media packet change events. This API is called by the controller.
7359
7360**System capability**: SystemCapability.Multimedia.AVSession.Core
7361
7362**Parameters**
7363
7364| Name     | Type                             | Mandatory | Description                                                  |
7365| -------- | -------------------------------- | --------- | ------------------------------------------------------------ |
7366| type     | string                           | Yes       | Event type, which is **'extrasChange'** in this case.        |
7367| callback | ({[key:string]: Object}) => void | No        | Callback used for unsubscription.<br>The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. |
7368
7369**Error codes**
7370
7371For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md).
7372
7373| ID      | Error Message                          |
7374| ------- | -------------------------------------- |
7375| 6600101 | Session service exception.             |
7376| 6600103 | The session controller does not exist. |
7377
7378**Example**
7379
7380```ts
7381avsessionController.off('extrasChange');
7382```
7383
7384## AVControlCommandType<sup>10+</sup>
7385
7386Enumerates the commands that can be sent to a session.
7387
7388**System capability**: SystemCapability.Multimedia.AVSession.Core
7389
7390| Name           | Type   | Description                    |
7391| -------------- | ------ | ------------------------------ |
7392| play           | string | Play the media.                |
7393| pause          | string | Pause the playback.            |
7394| stop           | string | Stop the playback.             |
7395| playNext       | string | Play the next media asset.     |
7396| playPrevious   | string | Play the previous media asset. |
7397| fastForward    | string | Fast-forward.                  |
7398| rewind         | string | Rewind.                        |
7399| seek           | string | Seek to a playback position.   |
7400| setSpeed       | string | Set the playback speed.        |
7401| setLoopMode    | string | Set the loop mode.             |
7402| toggleFavorite | string | Favorite the media asset.      |
7403
7404## AVControlCommand<sup>10+</sup>
7405
7406Describes the command that can be sent to the session.
7407
7408**System capability**: SystemCapability.Multimedia.AVSession.Core
7409
7410| Name      | Type                                                | Mandatory | Description                        |
7411| --------- | --------------------------------------------------- | --------- | ---------------------------------- |
7412| command   | [AVControlCommandType](#avcontrolcommandtype10)     | Yes       | Command.                           |
7413| parameter | [LoopMode](#loopmode10) &#124; string &#124; number | No        | Parameters carried in the command. |
7414
7415## AVSessionErrorCode<sup>10+</sup>
7416
7417Enumerates the error codes used in the media session.
7418
7419**System capability**: SystemCapability.Multimedia.AVSession.Core
7420
7421| Name                                 | Value   | Description                               |
7422| ------------------------------------ | ------- | ----------------------------------------- |
7423| ERR_CODE_SERVICE_EXCEPTION           | 6600101 | Session service exception.                |
7424| ERR_CODE_SESSION_NOT_EXIST           | 6600102 | The session does not exist.               |
7425| ERR_CODE_CONTROLLER_NOT_EXIST        | 6600103 | The session controller does not exist.    |
7426| ERR_CODE_REMOTE_CONNECTION_ERR       | 6600104 | The remote session  connection failed.    |
7427| ERR_CODE_COMMAND_INVALID             | 6600105 | Invalid session command.                  |
7428| ERR_CODE_SESSION_INACTIVE            | 6600106 | The session is not activated.             |
7429| ERR_CODE_MESSAGE_OVERLOAD            | 6600107 | Too many commands or events.              |
7430| ERR_CODE_DEVICE_CONNECTION_FAILED    | 6600108 | Device connecting failed.                 |
7431| ERR_CODE_REMOTE_CONNECTION_NOT_EXIST | 6600109 | The remote connection is not established. |
7432