1# @ohos.multimedia.avsession (AVSession Management) (System API)
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- [AVCastController](#avcastcontroller10): used to control playback, listen for remote playback state changes, and obtain the remote playback state in casting scenarios.
8
9> **NOTE**
10>
11> - 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.
12> - This topic describes only system APIs provided by the module. For details about its public APIs, see [@ohos.multimedia.avsession (AVSession Management)](js-apis-avsession.md).
13
14## Modules to Import
15
16```ts
17import { avSession } from '@kit.AVSessionKit';
18```
19
20## Usage Guidelines
21
22This topic describes only system APIs. Before using these APIs, you must create an instance. For details about how to create an instance, see the description and example of the public API [avSession.createAVSession](js-apis-avsession.md#avsessioncreateavsession10).
23
24## avSession.getAllSessionDescriptors
25
26getAllSessionDescriptors(): Promise\<Array\<Readonly\<AVSessionDescriptor>>>
27
28Obtains the descriptors of all sessions that have set media information and registered control callbacks. This API uses a promise to return the result.
29
30**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
31
32**System capability**: SystemCapability.Multimedia.AVSession.Manager
33
34**System API**: This is a system API.
35
36**Return value**
37
38| Type                                                        | Description                                         |
39| ------------------------------------------------------------ | --------------------------------------------- |
40| Promise\<Array\<Readonly\<[AVSessionDescriptor](#avsessiondescriptor)\>\>\> | Promise used to return an array of **AVSessionDescriptor** objects, each of which is read only.|
41
42**Error codes**
43
44For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
45
46| ID| Error Message|
47| -------- | ---------------------------------------- |
48| 201 | permission denied. |
49| 6600101  | Session service exception. |
50
51**Example**
52
53```ts
54import { BusinessError } from '@kit.BasicServicesKit';
55
56avSession.getAllSessionDescriptors().then((descriptors: avSession.AVSessionDescriptor[]) => {
57  console.info(`getAllSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`);
58  if (descriptors.length > 0 ) {
59    console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`);
60    console.info(`GetAllSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`);
61    console.info(`GetAllSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`);
62  }
63}).catch((err: BusinessError) => {
64  console.error(`GetAllSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`);
65});
66```
67
68## avSession.getAllSessionDescriptors
69
70getAllSessionDescriptors(callback: AsyncCallback\<Array\<Readonly\<AVSessionDescriptor>>>): void
71
72Obtains the descriptors of all sessions that have set media information and registered control callbacks. This API uses an asynchronous callback to return the result.
73
74**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
75
76**System capability**: SystemCapability.Multimedia.AVSession.Manager
77
78**System API**: This is a system API.
79
80**Parameters**
81
82| Name  | Type                                                        | Mandatory| Description                                      |
83| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ |
84| callback | AsyncCallback<Array<Readonly<[AVSessionDescriptor](#avsessiondescriptor)\>\>\> | Yes  | Callback used to return an array of **AVSessionDescriptor** objects, each of which is read only.|
85
86**Error codes**
87
88For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
89
90| ID| Error Message|
91| -------- | ---------------------------------------- |
92| 201 | permission denied. |
93| 6600101  |Session service exception. |
94
95**Example**
96
97```ts
98import { BusinessError } from '@kit.BasicServicesKit';
99
100avSession.getAllSessionDescriptors((err: BusinessError, descriptors: avSession.AVSessionDescriptor[]) => {
101  if (err) {
102    console.error(`GetAllSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`);
103  } else {
104    console.info(`GetAllSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`);
105    if (descriptors.length > 0 ) {
106        console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`);
107        console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`);
108        console.info(`getAllSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`);
109    }
110  }
111});
112```
113
114## avSession.getHistoricalSessionDescriptors<sup>10+</sup>
115
116getHistoricalSessionDescriptors(maxSize?: number): Promise\<Array\<Readonly\<AVSessionDescriptor>>>
117
118Obtains the descriptors of all historical sessions. This API uses a promise to return the result.
119
120**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
121
122**System capability**: SystemCapability.Multimedia.AVSession.Manager
123
124**System API**: This is a system API.
125
126**Parameters**
127
128| Name  | Type   | Mandatory| Description                                                            |
129| -------- | ------ | ---- | -----------------------------------------------------------------|
130| 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.|
131
132**Return value**
133
134| Type                                                                       | Description                                  |
135| --------------------------------------------------------------------------- | -------------------------------------- |
136| Promise\<Array\<Readonly\<[AVSessionDescriptor](#avsessiondescriptor)\>\>\> | Promise used to return an array of **AVSessionDescriptor** objects, each of which is read only.|
137
138**Error codes**
139
140For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
141
142| ID| Error Message|
143| -------- | ---------------------------------------- |
144| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
145| 6600101  | Session service exception. |
146
147**Example**
148
149```ts
150import { BusinessError } from '@kit.BasicServicesKit';
151
152avSession.getHistoricalSessionDescriptors().then((descriptors: avSession.AVSessionDescriptor[]) => {
153  console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`);
154  if (descriptors.length > 0 ) {
155    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`);
156    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`);
157    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`);
158    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionId : ${descriptors[0].sessionId}`);
159    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].elementName.bundleName : ${descriptors[0].elementName.bundleName}`);
160  }
161}).catch((err: BusinessError) => {
162  console.error(`getHistoricalSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`);
163});
164```
165
166## avSession.getHistoricalSessionDescriptors<sup>10+</sup>
167
168getHistoricalSessionDescriptors(maxSize: number, callback: AsyncCallback\<Array\<Readonly\<AVSessionDescriptor>>>): void
169
170Obtains the descriptors of all historical sessions. This API uses an asynchronous callback to return the result.
171
172**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
173
174**System capability**: SystemCapability.Multimedia.AVSession.Manager
175
176**System API**: This is a system API.
177
178**Parameters**
179
180| Name  | Type                                                                           | Mandatory| Description                                                            |
181| -------- | ------------------------------------------------------------------------------ | ---- | -----------------------------------------------------------------|
182| maxSize  | number                                                                         | Yes | Maximum number of descriptors to obtain. The value ranges from 0 to 10.|
183| callback | AsyncCallback<Array<Readonly<[AVSessionDescriptor](#avsessiondescriptor)\>\>\> | Yes  | Callback used to return an array of **AVSessionDescriptor** objects, each of which is read only.                             |
184
185**Error codes**
186
187For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
188
189| ID| Error Message|
190| -------- | ---------------------------------------- |
191| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
192| 6600101  |Session service exception. |
193
194**Example**
195
196```ts
197import { BusinessError } from '@kit.BasicServicesKit';
198
199avSession.getHistoricalSessionDescriptors(1, (err: BusinessError, descriptors: avSession.AVSessionDescriptor[]) => {
200  if (err) {
201    console.error(`getHistoricalSessionDescriptors BusinessError: code: ${err.code}, message: ${err.message}`);
202  } else {
203    console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`);
204    if (descriptors.length > 0 ) {
205      console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`);
206      console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`);
207      console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`);
208      console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionId : ${descriptors[0].sessionId}`);
209      console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].elementName.bundleName : ${descriptors[0].elementName.bundleName}`);
210    }
211  }
212});
213```
214
215## avSession.getHistoricalAVQueueInfos<sup>11+</sup>
216
217getHistoricalAVQueueInfos(maxSize: number, maxAppSize: number) : Promise\<Array\<Readonly\<AVQueueInfo>>>
218
219Obtains all the historical playlists. This API uses a promise to return the result.
220
221**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
222
223**System capability**: SystemCapability.Multimedia.AVSession.Manager
224
225**System API**: This is a system API.
226
227**Parameters**
228
229| Name  | Type   | Mandatory| Description                                                            |
230| -------- | ------ | ---- | ---------------------------------------------------------------|
231| maxSize  | number | Yes  | Maximum number of playlists that can be obtained. Currently, the maximum number is restricted by the system.                    |
232| maxAppSize | number | Yes  | Maximum number of applications to which the playlists to be obtained belong. Currently, the maximum number is restricted by the system.            |
233
234**Return value**
235
236| Type                                                                       | Description                                  |
237| --------------------------------------------------------------------------- | ------------------------------------- |
238| Promise\<Array\<Readonly\<[AVQueueInfo](#avqueueinfo11)\>\>\> | Promise used to return all the read-only historical playlists.               |
239
240**Error codes**
241
242For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
243
244| ID| Error Message|
245| -------- | ---------------------------------------- |
246| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
247| 6600101  | Session service exception. |
248
249**Example**
250
251```ts
252import { BusinessError } from '@kit.BasicServicesKit';
253
254avSession.getHistoricalAVQueueInfos(3, 5).then((avQueueInfos: avSession.AVQueueInfo[]) => {
255  console.info(`getHistoricalAVQueueInfos : SUCCESS : avQueueInfos.length : ${avQueueInfos.length}`);
256}).catch((err: BusinessError) => {
257  console.error(`getHistoricalAVQueueInfos BusinessError: code: ${err.code}, message: ${err.message}`);
258});
259```
260
261## avSession.getHistoricalAVQueueInfos<sup>11+</sup>
262
263getHistoricalAVQueueInfos(maxSize: number, maxAppSize: number, callback: AsyncCallback\<Array\<Readonly\<AVQueueInfo>>>): void;
264
265Obtains all the historical playlists. This API uses an asynchronous callback to return the result.
266
267**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
268
269**System capability**: SystemCapability.Multimedia.AVSession.Manager
270
271**System API**: This is a system API.
272
273**Parameters**
274
275| Name  | Type                                                                           | Mandatory| Description                                                            |
276| -------- | ----------------------------------------------------------------------------- | ---- | ---------------------------------------------------------------|
277| maxSize  | number                                                                        | Yes  | Maximum number of playlists that can be obtained. Currently, the maximum number is restricted by the system.                     |
278| maxAppSize | number                                                                      | Yes  | Maximum number of applications to which the playlists to be obtained belong. Currently, the maximum number is restricted by the system.              |
279| callback | AsyncCallback<Array<Readonly<[AVQueueInfo](#avqueueinfo11)\>\>\> | Yes  | Callback used to return all the read-only historical playlists.                             |
280
281**Error codes**
282
283For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
284
285| ID| Error Message|
286| -------- | ---------------------------------------- |
287| 201 | permission denied. |
288| 202 | Not System App. |
289| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
290| 6600101  |Session service exception. |
291
292**Example**
293
294```ts
295import { BusinessError } from '@kit.BasicServicesKit';
296
297avSession.getHistoricalAVQueueInfos(3, 5, (err: BusinessError, avQueueInfos: avSession.AVQueueInfo[]) => {
298  if (err) {
299    console.error(`getHistoricalAVQueueInfos BusinessError: code: ${err.code}, message: ${err.message}`);
300  } else {
301    console.info(`getHistoricalAVQueueInfos : SUCCESS : avQueueInfos.length : ${avQueueInfos.length}`);
302  }
303});
304```
305
306## avSession.createController
307
308createController(sessionId: string): Promise\<AVSessionController>
309
310Creates a session controller based on the session ID. Multiple session controllers can be created. This API uses a promise to return the result.
311
312**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
313
314**System capability**: SystemCapability.Multimedia.AVSession.Manager
315
316**System API**: This is a system API.
317
318**Parameters**
319
320| Name   | Type  | Mandatory| Description    |
321| --------- | ------ | ---- | -------- |
322| sessionId | string | Yes  | Session ID. If the value is set to **'default'**, the system creates a default controller to control the system default session.|
323
324**Return value**
325
326| Type                                                 | Description                                                        |
327| ----------------------------------------------------- | ------------------------------------------------------------ |
328| Promise<[AVSessionController](js-apis-avsession.md#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.|
329
330**Error codes**
331
332For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
333
334| ID| Error Message|
335| -------- | ---------------------------------------- |
336| 201 | permission denied. |
337| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
338| 6600101  | Session service exception. |
339| 6600102  | The session does not exist. |
340
341**Example**
342
343```ts
344import { BusinessError } from '@kit.BasicServicesKit';
345
346let currentAVcontroller: avSession.AVSessionController | undefined = undefined;
347currentAvSession.createController(sessionId).then((avcontroller: avSession.AVSessionController) => {
348  currentAVcontroller = avcontroller;
349  console.info('CreateController : SUCCESS ');
350}).catch((err: BusinessError) => {
351  console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
352});
353```
354
355## avSession.createController
356
357createController(sessionId: string, callback: AsyncCallback\<AVSessionController>): void
358
359Creates a session controller based on the session ID. Multiple session controllers can be created. This API uses an asynchronous callback to return the result.
360
361**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
362
363**System capability**: SystemCapability.Multimedia.AVSession.Manager
364
365**System API**: This is a system API.
366
367**Parameters**
368
369| Name   | Type                                                       | Mandatory| Description                                                        |
370| --------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
371| sessionId | string                                                      | Yes  | Session ID. If the value is set to **'default'**, the system creates a default controller to control the default session.                                                    |
372| callback  | AsyncCallback<[AVSessionController](js-apis-avsession.md#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.|
373
374**Error codes**
375
376For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
377
378| ID| Error Message|
379| -------- | ---------------------------------------- |
380| 201 | permission denied. |
381| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
382| 6600101  | Session service exception. |
383| 6600102  | The session does not exist. |
384
385**Example**
386
387```ts
388import { BusinessError } from '@kit.BasicServicesKit';
389
390let currentAVcontroller: avSession.AVSessionController | undefined = undefined;
391currentAvSession.createController(sessionId, (err: BusinessError, avcontroller: avSession.AVSessionController) => {
392  if (err) {
393    console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
394  } else {
395    currentAVcontroller = avcontroller;
396    console.info('CreateController : SUCCESS ');
397  }
398});
399```
400
401## avSession.castAudio
402
403castAudio(session: SessionToken | 'all', audioDevices: Array<audio.AudioDeviceDescriptor>): Promise\<void>
404
405Casts a session to a list of devices. This API uses a promise to return the result.
406
407Before calling this API, import the **ohos.multimedia.audio** module to obtain the descriptors of these audio devices.
408
409**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
410
411**System capability**: SystemCapability.Multimedia.AVSession.Manager
412
413**System API**: This is a system API.
414
415**Parameters**
416
417| Name       | Type          | Mandatory| Description|
418| ------------ | -------------- |------|------|
419| session      | [SessionToken](#sessiontoken) &#124; 'all' | Yes  | Session token. **SessionToken** indicates a specific token, and **'all'** indicates all tokens.|
420| audioDevices | Array\<[audio.AudioDeviceDescriptor](../apis-audio-kit/js-apis-audio.md#audiodevicedescriptor)\> | Yes  | Audio devices. |
421
422**Return value**
423
424| Type          | Description                         |
425| -------------- | ----------------------------- |
426| Promise\<void> | Promise used to return the result. If casting is successful, no value is returned; otherwise, an error object is returned.|
427
428**Error codes**
429
430For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
431
432| ID| Error Message|
433| -------- | ---------------------------------------- |
434| 201 | permission denied. |
435| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
436| 6600101  | Session service exception. |
437| 6600102  | The session does not exist. |
438| 6600104  | The remote session connection failed. |
439
440**Example**
441
442```ts
443import { audio } from '@kit.AudioKit';
444import { BusinessError } from '@kit.BasicServicesKit';
445
446let audioManager = audio.getAudioManager();
447let audioRoutingManager = audioManager.getRoutingManager();
448let audioDevices: audio.AudioDeviceDescriptors | undefined = undefined;
449audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
450  audioDevices = data;
451  console.info('Promise returned to indicate that the device list is obtained.');
452}).catch((err: BusinessError) => {
453  console.error(`GetDevices BusinessError: code: ${err.code}, message: ${err.message}`);
454});
455
456if (audioDevices !== undefined) {
457  avSession.castAudio('all', audioDevices as audio.AudioDeviceDescriptors).then(() => {
458    console.info('CreateController : SUCCESS');
459  }).catch((err: BusinessError) => {
460    console.error(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`);
461  });
462}
463```
464
465## avSession.castAudio
466
467castAudio(session: SessionToken | 'all', audioDevices: Array<audio.AudioDeviceDescriptor>, callback: AsyncCallback\<void>): void
468
469Casts a session to a list of devices. This API uses an asynchronous callback to return the result.
470
471Before calling this API, import the **ohos.multimedia.audio** module to obtain the descriptors of these audio devices.
472
473**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
474
475**System capability**: SystemCapability.Multimedia.AVSession.Manager
476
477**System API**: This is a system API.
478
479**Parameters**
480
481| Name      | Type                                        | Mandatory| Description                                                        |
482| ------------ |--------------------------------------------| ---- | ------------------------------------------------------------ |
483| session      | [SessionToken](#sessiontoken) &#124; 'all' | Yes  | Session token. **SessionToken** indicates a specific token, and **'all'** indicates all tokens.|
484| audioDevices | Array\<[audio.AudioDeviceDescriptor](../apis-audio-kit/js-apis-audio.md#audiodevicedescriptor)\>   | Yes  | Audio devices.|
485| callback     | AsyncCallback\<void>     | Yes  | Callback used to return the result. If casting is successful, **err** is **undefined**; otherwise, **err** is an error object.     |
486
487**Error codes**
488
489For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
490
491| ID| Error Message|
492| -------- | ---------------------------------------- |
493| 201 | permission denied. |
494| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
495| 6600101  | Session service exception. |
496| 6600102  | The session does not exist. |
497| 6600104  | The remote session connection failed. |
498
499**Example**
500
501```ts
502import { audio } from '@kit.AudioKit';
503import { BusinessError } from '@kit.BasicServicesKit';
504
505let audioManager = audio.getAudioManager();
506let audioRoutingManager = audioManager.getRoutingManager();
507let audioDevices: audio.AudioDeviceDescriptors | undefined = undefined;
508audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
509  audioDevices = data;
510  console.info('Promise returned to indicate that the device list is obtained.');
511}).catch((err: BusinessError) => {
512  console.error(`GetDevices BusinessError: code: ${err.code}, message: ${err.message}`);
513});
514
515if (audioDevices !== undefined) {
516  avSession.castAudio('all', audioDevices as audio.AudioDeviceDescriptors, (err: BusinessError) => {
517    if (err) {
518      console.error(`CastAudio BusinessError: code: ${err.code}, message: ${err.message}`);
519    } else {
520      console.info('CastAudio : SUCCESS ');
521    }
522  });
523}
524```
525
526## avSession.startAVPlayback<sup>11+</sup>
527
528startAVPlayback(bundleName: string, assetId: string): Promise\<void>
529
530Starts an application to play a media asset. This API uses a promise to return the result.
531
532**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
533
534**System capability**: SystemCapability.Multimedia.AVSession.Manager
535
536**System API**: This is a system API.
537
538**Parameters**
539
540| Name       | Type          | Mandatory| Description|
541| ------------ | -------------- |------|------|
542| bundleName   | string         | Yes  | Bundle name of the application.|
543| assetId      |string           | Yes  | ID of the media asset. |
544
545**Return value**
546
547| Type          | Description                         |
548| -------------- | ----------------------------- |
549| Promise\<void> | Promise used to return the result. If the playback is successful, no value is returned; otherwise, an error object is returned.|
550
551**Error codes**
552
553For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
554
555| ID| Error Message|
556| -------- | ---------------------------------------- |
557| 201 | permission denied. |
558| 202 | Not System App. Interface caller is not a system app. |
559| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
560| 6600101  | Session service exception. |
561
562**Example**
563
564```ts
565import { audio } from '@kit.AudioKit';
566import { BusinessError } from '@kit.BasicServicesKit';
567
568avSession.startAVPlayback("com.example.myapplication", "121278").then(() => {
569  console.info('startAVPlayback : SUCCESS');
570}).catch((err: BusinessError) => {
571  console.error(`startAVPlayback BusinessError: code: ${err.code}, message: ${err.message}`);
572});
573```
574
575## SessionToken
576
577Describes the information about a session token.
578
579**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
580
581**System capability**: SystemCapability.Multimedia.AVSession.Manager
582
583**System API**: This is a system API.
584
585| Name     | Type  | Mandatory| Description        |
586| :-------- | :----- | :--- | :----------- |
587| sessionId | string | Yes  | Session ID.      |
588| pid       | number | No  | Process ID of the session.|
589| uid       | number | No  | User ID.      |
590
591## avSession.on('sessionCreate')
592
593on(type: 'sessionCreate', callback: (session: AVSessionDescriptor) => void): void
594
595Subscribes to session creation events.
596
597**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
598
599**System capability**: SystemCapability.Multimedia.AVSession.Manager
600
601**System API**: This is a system API.
602
603**Parameters**
604
605| Name   | Type                  | Mandatory| Description                                                        |
606| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
607| type     | string                 | Yes  | Event type. The event **'sessionCreate'** is triggered when a session is created.|
608| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | Yes  | Callback used to report the session descriptor.|
609
610**Error codes**
611
612For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
613
614| ID| Error Message|
615| -------- | ---------------------------------------- |
616| 201 | permission denied. |
617| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
618| 6600101  | Session service exception. |
619
620**Example**
621
622```ts
623avSession.on('sessionCreate', (descriptor: avSession.AVSessionDescriptor) => {
624  console.info(`on sessionCreate : isActive : ${descriptor.isActive}`);
625  console.info(`on sessionCreate : type : ${descriptor.type}`);
626  console.info(`on sessionCreate : sessionTag : ${descriptor.sessionTag}`);
627});
628
629```
630
631## avSession.on('sessionDestroy')
632
633on(type: 'sessionDestroy', callback: (session: AVSessionDescriptor) => void): void
634
635Subscribes to session destruction events.
636
637**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
638
639**System capability**: SystemCapability.Multimedia.AVSession.Manager
640
641**System API**: This is a system API.
642
643**Parameters**
644
645| Name  | Type           | Mandatory| Description                                                        |
646| -------- | ---------------| ---- | ------------------------------------------------------------ |
647| type     | string         | Yes  | Event type. The event **'sessionDestroy'** is triggered when a session is destroyed.|
648| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | Yes  | Callback used to report the session descriptor.|
649
650**Error codes**
651
652For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
653
654| ID| Error Message|
655| -------- | ---------------------------------------- |
656| 201 | permission denied. |
657| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
658| 6600101  | Session service exception. |
659
660**Example**
661
662```ts
663avSession.on('sessionDestroy', (descriptor: avSession.AVSessionDescriptor) => {
664  console.info(`on sessionDestroy : isActive : ${descriptor.isActive}`);
665  console.info(`on sessionDestroy : type : ${descriptor.type}`);
666  console.info(`on sessionDestroy : sessionTag : ${descriptor.sessionTag}`);
667});
668```
669
670## avSession.on('topSessionChange')
671
672on(type: 'topSessionChange', callback: (session: AVSessionDescriptor) => void): void
673
674Subscribes to top session change events.
675
676**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
677
678**System capability**: SystemCapability.Multimedia.AVSession.Manager
679
680**System API**: This is a system API.
681
682**Parameters**
683
684| Name  | Type                | Mandatory| Description                                                        |
685| -------- | --------------------| ---- | ------------------------------------------------------------ |
686| type     | string      | Yes  | Event type. The event **'topSessionChange'** is triggered when the top session is changed.|
687| callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | Yes  | Callback used to report the session descriptor.|
688
689**Error codes**
690
691For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
692
693| ID| Error Message|
694| -------- | ---------------------------------------- |
695| 201 | permission denied. |
696| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
697| 6600101  | Session service exception. |
698
699**Example**
700
701```ts
702avSession.on('topSessionChange', (descriptor: avSession.AVSessionDescriptor) => {
703  console.info(`on topSessionChange : isActive : ${descriptor.isActive}`);
704  console.info(`on topSessionChange : type : ${descriptor.type}`);
705  console.info(`on topSessionChange : sessionTag : ${descriptor.sessionTag}`);
706});
707```
708
709## avSession.off('sessionCreate')
710
711off(type: 'sessionCreate', callback?: (session: AVSessionDescriptor) => void): void
712
713Unsubscribes from session creation events.
714
715**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
716
717**System capability**: SystemCapability.Multimedia.AVSession.Manager
718
719**System API**: This is a system API.
720
721**Parameters**
722
723| Name  | Type      | Mandatory| Description      |
724| -------- | ----------| ---- | ----------|
725| type     | string    | Yes  | Event type, which is **'sessionCreate'** in this case.|
726| 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.                              |
727
728**Error codes**
729
730For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
731
732| ID| Error Message|
733| -------- | ---------------------------------------- |
734| 201 | permission denied. |
735| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
736| 6600101  | Session service exception. |
737
738**Example**
739
740```ts
741avSession.off('sessionCreate');
742```
743
744## avSession.off('sessionDestroy')
745
746off(type: 'sessionDestroy', callback?: (session: AVSessionDescriptor) => void): void
747
748Unsubscribes from session destruction events.
749
750**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
751
752**System capability**: SystemCapability.Multimedia.AVSession.Manager
753
754**System API**: This is a system API.
755
756**Parameters**
757
758| Name  | Type       | Mandatory| Description                     |
759| -------- | -----------| ---- | -------------------------|
760| type     | string     | Yes  | Event type, which is **'sessionDestroy'** in this case.|
761| 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.|
762
763**Error codes**
764
765For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
766
767| ID| Error Message|
768| -------- | ---------------------------------------- |
769| 201 | permission denied. |
770| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
771| 6600101  | Session service exception. |
772
773**Example**
774
775```ts
776avSession.off('sessionDestroy');
777```
778
779## avSession.off('topSessionChange')
780
781off(type: 'topSessionChange', callback?: (session: AVSessionDescriptor) => void): void
782
783Unsubscribes from top session change events.
784
785**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
786
787**System capability**: SystemCapability.Multimedia.AVSession.Manager
788
789**System API**: This is a system API.
790
791**Parameters**
792
793| Name  | Type             | Mandatory| Description                       |
794| -------- | -----------------| ---- | ---------------------------- |
795| type     | string           | Yes  | Event type, which is **'topSessionChange'** in this case.|
796| 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.|
797
798**Error codes**
799
800For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
801
802| ID| Error Message|
803| -------- | ---------------------------------------- |
804| 201 | permission denied. |
805| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
806| 6600101  | Session service exception. |
807
808**Example**
809
810```ts
811avSession.off('topSessionChange');
812```
813
814## avSession.on('sessionServiceDie')
815
816on(type: 'sessionServiceDie', callback: () => void): void
817
818Subscribes to session service death events. Upon receiving this event, the application can clear resources.
819
820**System capability**: SystemCapability.Multimedia.AVSession.Core
821
822**System API**: This is a system API.
823
824**Parameters**
825
826| Name  | Type                | Mandatory| Description                                                        |
827| -------- | -------------------- | ---- | ------------------------------------------------------------ |
828| type     | string               | Yes  | Event type. The event **'sessionServiceDie'** is triggered when the session service dies.|
829| callback | callback: () => void | Yes  | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object.                               |
830
831**Error codes**
832
833For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
834
835| ID| Error Message|
836| -------- | ---------------------------------------- |
837| 201 | permission denied. |
838| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
839| 6600101  | Session service exception. |
840
841**Example**
842
843```ts
844avSession.on('sessionServiceDie', () => {
845  console.info('on sessionServiceDie  : session is  Died ');
846});
847```
848
849## avSession.off('sessionServiceDie')
850
851off(type: 'sessionServiceDie', callback?: () => void): void
852
853Unsubscribes from session service death events.
854
855**System capability**: SystemCapability.Multimedia.AVSession.Core
856
857**System API**: This is a system API.
858
859**Parameters**
860
861| Name   | Type                   | Mandatory |      Description                                              |
862| ------   | ---------------------- | ---- | ------------------------------------------------------- |
863| type     | string                 | Yes   | Event type. The event **'sessionServiceDie'** is triggered when the session service dies.|
864| 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.           |
865
866**Error codes**
867
868For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
869
870| ID| Error Message|
871| -------- | ---------------------------------------- |
872| 201 | permission denied. |
873| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
874| 6600101  | Session service exception. |
875
876**Example**
877
878```ts
879avSession.off('sessionServiceDie');
880```
881
882## avSession.sendSystemAVKeyEvent
883
884sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback\<void>): void
885
886Sends a system key event to the top session. This API uses an asynchronous callback to return the result.
887
888**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
889
890**System capability**: SystemCapability.Multimedia.AVSession.Manager
891
892**System API**: This is a system API.
893
894**Parameters**
895
896| Name  | Type                                                        | Mandatory| Description                                 |
897| -------- | ------------------------------------------------------------ | ---- | ------------------------------------- |
898| event    | [KeyEvent](../apis-input-kit/js-apis-keyevent.md#keyevent) | Yes  | Key event.                           |
899| callback | AsyncCallback\<void>                                         | Yes  | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.|
900
901**Error codes**
902
903For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
904
905| ID| Error Message|
906| -------- | ---------------------------------------- |
907| 201 | permission denied. |
908| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
909| 6600101  | Session service exception. |
910| 6600105  | Invalid session command. |
911
912**Example**
913
914```ts
915import { KeyEvent } from '@kit.InputKit';
916import { BusinessError } from '@kit.BasicServicesKit';
917
918let keyItem: keyEvent.Key = {code:0x49, pressedTime:2, deviceId:0};
919let 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};
920
921avSession.sendSystemAVKeyEvent(event, (err: BusinessError) => {
922  if (err) {
923    console.error(`SendSystemAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`);
924  } else {
925    console.info('SendSystemAVKeyEvent : SUCCESS ');
926  }
927});
928```
929
930## avSession.sendSystemAVKeyEvent
931
932sendSystemAVKeyEvent(event: KeyEvent): Promise\<void>
933
934Sends a system key event to the top session. This API uses a promise to return the result.
935
936**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
937
938**System capability**: SystemCapability.Multimedia.AVSession.Manager
939
940**System API**: This is a system API.
941
942**Parameters**
943
944| Name| Type                           | Mandatory| Description      |
945| ------ | ------------------------------- | ---- | ---------- |
946| event  | [KeyEvent](../apis-input-kit/js-apis-keyevent.md#keyevent) | Yes  | Key event.|
947
948**Return value**
949
950| Type          | Description                         |
951| -------------- | ----------------------------- |
952| Promise\<void> | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.|
953
954**Error codes**
955
956For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
957
958| ID| Error Message|
959| -------- | ---------------------------------------- |
960| 201 | permission denied. |
961| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
962| 6600101  | Session service exception. |
963| 6600105  | Invalid session command. |
964
965**Example**
966
967```ts
968import { KeyEvent } from '@kit.InputKit';
969import { BusinessError } from '@kit.BasicServicesKit';
970
971let keyItem: keyEvent.Key = {code:0x49, pressedTime:2, deviceId:0};
972let 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};
973
974avSession.sendSystemAVKeyEvent(event).then(() => {
975  console.info('SendSystemAVKeyEvent Successfully');
976}).catch((err: BusinessError) => {
977  console.error(`SendSystemAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`);
978});
979```
980
981## avSession.sendSystemControlCommand
982
983sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback\<void>): void
984
985Sends a system control command to the top session. This API uses an asynchronous callback to return the result.
986
987**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
988
989**System capability**: SystemCapability.Multimedia.AVSession.Manager
990
991**System API**: This is a system API.
992
993**Parameters**
994
995| Name  | Type                                 | Mandatory| Description                                 |
996| -------- | ------------------------------------- | ---- | ------------------------------------- |
997| command  | [AVControlCommand](js-apis-avsession.md#avcontrolcommand10) | Yes  | Command to send.  |
998| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object.|
999
1000**Error codes**
1001
1002For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1003
1004| ID| Error Message|
1005| -------- | ---------------------------------------- |
1006| 201 | permission denied. |
1007| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
1008| 6600101  | Session service exception. |
1009| 6600105  | Invalid session command. |
1010| 6600107  | Too many commands or events. |
1011
1012**Example**
1013
1014```ts
1015let cmd : avSession.AVControlCommandType = 'play';
1016// let cmd : avSession.AVControlCommandType = 'pause';
1017// let cmd : avSession.AVControlCommandType = 'stop';
1018// let cmd : avSession.AVControlCommandType = 'playNext';
1019// let cmd : avSession.AVControlCommandType = 'playPrevious';
1020// let cmd : avSession.AVControlCommandType = 'fastForward';
1021// let cmd : avSession.AVControlCommandType = 'rewind';
1022let avcommand: avSession.AVControlCommand = {command:cmd};
1023// let cmd : avSession.AVControlCommandType = 'seek';
1024// let avcommand = {command:cmd, parameter:10};
1025// let cmd : avSession.AVControlCommandType = 'setSpeed';
1026// let avcommand = {command:cmd, parameter:2.6};
1027// let cmd : avSession.AVControlCommandType = 'setLoopMode';
1028// let avcommand = {command:cmd, parameter:avSession.LoopMode.LOOP_MODE_SINGLE};
1029// let cmd : avSession.AVControlCommandType = 'toggleFavorite';
1030// let avcommand = {command:cmd, parameter:"false"};
1031avSession.sendSystemControlCommand(avcommand, (err) => {
1032  if (err) {
1033    console.error(`SendSystemControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
1034  } else {
1035    console.info('sendSystemControlCommand successfully');
1036  }
1037});
1038```
1039
1040## avSession.sendSystemControlCommand
1041
1042sendSystemControlCommand(command: AVControlCommand): Promise\<void>
1043
1044Sends a system control command to the top session. This API uses a promise to return the result.
1045
1046**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
1047
1048**System capability**: SystemCapability.Multimedia.AVSession.Manager
1049
1050**System API**: This is a system API.
1051
1052**Parameters**
1053
1054| Name | Type                                 | Mandatory| Description                               |
1055| ------- | ------------------------------------- | ---- | ----------------------------------- |
1056| command | [AVControlCommand](js-apis-avsession.md#avcontrolcommand10) | Yes  | Command to send.|
1057
1058**Return value**
1059
1060| Type          | Description                         |
1061| -------------- | ----------------------------- |
1062| Promise\<void> | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.|
1063
1064**Error codes**
1065
1066For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1067
1068| ID| Error Message|
1069| -------- | ---------------------------------------- |
1070| 201 | permission denied. |
1071| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
1072| 6600101  | Session service exception. |
1073| 6600105  | Invalid session command. |
1074| 6600107  | Too many commands or events. |
1075
1076**Example**
1077
1078```ts
1079import { BusinessError } from '@kit.BasicServicesKit';
1080
1081let cmd : avSession.AVControlCommandType = 'play';
1082// let cmd : avSession.AVControlCommandType = 'pause';
1083// let cmd : avSession.AVControlCommandType = 'stop';
1084// let cmd : avSession.AVControlCommandType = 'playNext';
1085// let cmd : avSession.AVControlCommandType = 'playPrevious';
1086// let cmd : avSession.AVControlCommandType = 'fastForward';
1087// let cmd : avSession.AVControlCommandType = 'rewind';
1088let avcommand: avSession.AVControlCommand = {command:cmd};
1089// let cmd : avSession.AVControlCommandType = 'seek';
1090// let avcommand = {command:cmd, parameter:10};
1091// let cmd : avSession.AVControlCommandType = 'setSpeed';
1092// let avcommand = {command:cmd, parameter:2.6};
1093// let cmd : avSession.AVControlCommandType = 'setLoopMode';
1094// let avcommand = {command:cmd, parameter:avSession.LoopMode.LOOP_MODE_SINGLE};
1095// let cmd : avSession.AVControlCommandType = 'toggleFavorite';
1096// let avcommand = {command:cmd, parameter:"false"};
1097avSession.sendSystemControlCommand(avcommand).then(() => {
1098  console.info('SendSystemControlCommand successfully');
1099}).catch((err: BusinessError) => {
1100  console.error(`SendSystemControlCommand BusinessError: code: ${err.code}, message: ${err.message}`);
1101});
1102```
1103
1104## ProtocolType<sup>10+</sup>
1105
1106Enumerates the protocol types supported by the remote device.
1107
1108**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1109
1110| Name                       | Value  | Description        |
1111| --------------------------- | ---- | ----------- |
1112| TYPE_CAST_PLUS_MIRROR      | 1    | Cast+ mirror mode.<br> **System API**: This is a system API.|
1113
1114## avSession.startCastDeviceDiscovery<sup>10+</sup>
1115
1116startCastDeviceDiscovery(callback: AsyncCallback\<void>): void
1117
1118Starts cast-enabled device discovery. 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| 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.|
1129
1130
1131**Example**
1132
1133```ts
1134import { BusinessError } from '@kit.BasicServicesKit';
1135
1136avSession.startCastDeviceDiscovery((err: BusinessError) => {
1137  if (err) {
1138    console.error(`startCastDeviceDiscovery BusinessError: code: ${err.code}, message: ${err.message}`);
1139  } else {
1140    console.info('startCastDeviceDiscovery successfully');
1141  }
1142});
1143```
1144
1145## avSession.startCastDeviceDiscovery<sup>10+</sup>
1146
1147startCastDeviceDiscovery(filter: number, callback: AsyncCallback\<void>): void
1148
1149Starts cast-enabled device discovery with filter criteria specified. This API uses an asynchronous callback to return the result.
1150
1151**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1152
1153**System API**: This is a system API.
1154
1155**Parameters**
1156
1157| Name  | Type                                 | Mandatory| Description                                 |
1158| -------- | ------------------------------------- | ---- | ------------------------------------- |
1159| filter | number | Yes| Filter criteria for device discovery. The value consists of **ProtocolType**s.|
1160| 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.|
1161
1162**Error codes**
1163
1164For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1165
1166| ID| Error Message|
1167| -------- | ---------------------------------------- |
1168| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
1169
1170**Example**
1171
1172```ts
1173import { BusinessError } from '@kit.BasicServicesKit';
1174
1175let filter = 2;
1176avSession.startCastDeviceDiscovery(filter, (err: BusinessError) => {
1177  if (err) {
1178    console.error(`startCastDeviceDiscovery BusinessError: code: ${err.code}, message: ${err.message}`);
1179  } else {
1180    console.info('startCastDeviceDiscovery successfully');
1181  }
1182});
1183```
1184
1185## avSession.startCastDeviceDiscovery<sup>10+</sup>
1186
1187startCastDeviceDiscovery(filter?: number, drmSchemes?: Array\<string>): Promise\<void>
1188
1189Starts cast-enabled device discovery. This API uses a promise to return the result.
1190
1191**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1192
1193**System API**: This is a system API.
1194
1195**Parameters**
1196
1197| Name  | Type                                 | Mandatory| Description                                 |
1198| -------- | ------------------------------------- | ---- | ------------------------------------- |
1199| filter | number | No| Filter criteria for device discovery. The value consists of **ProtocolType**s.|
1200| drmSchemes | Array\<string> | No| Filter criteria for discovering devices that support DRM resource playback. The value consists of DRM UUIDs.<br>This parameter is supported since API version 12.|
1201
1202**Return value**
1203
1204| Type          | Description                         |
1205| -------------- | ----------------------------- |
1206| 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.|
1207
1208**Error codes**
1209
1210For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1211
1212| ID| Error Message|
1213| -------- | ---------------------------------------- |
1214| 202 | Not System App. |
1215| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
1216
1217**Example**
1218
1219```ts
1220import { BusinessError } from '@kit.BasicServicesKit';
1221
1222let filter = 2;
1223let drmSchemes = ['3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c'];
1224avSession.startCastDeviceDiscovery(filter, drmSchemes).then(() => {
1225  console.info('startCastDeviceDiscovery successfully');
1226}).catch((err: BusinessError) => {
1227  console.error(`startCastDeviceDiscovery BusinessError: code: ${err.code}, message: ${err.message}`);
1228});
1229```
1230
1231## avSession.stopCastDeviceDiscovery<sup>10+</sup>
1232
1233stopCastDeviceDiscovery(callback: AsyncCallback\<void>): void
1234
1235Stops cast-enabled device discovery. This API uses an asynchronous callback to return the result.
1236
1237**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1238
1239**System API**: This is a system API.
1240
1241**Parameters**
1242
1243| Name  | Type                                 | Mandatory| Description                                 |
1244| -------- | ------------------------------------- | ---- | ------------------------------------- |
1245| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If device discovery stops, **err** is **undefined**; otherwise, **err** is an error object.|
1246
1247
1248**Example**
1249
1250```ts
1251import { BusinessError } from '@kit.BasicServicesKit';
1252
1253avSession.stopCastDeviceDiscovery((err: BusinessError) => {
1254  if (err) {
1255    console.error(`stopCastDeviceDiscovery BusinessError: code: ${err.code}, message: ${err.message}`);
1256  } else {
1257    console.info('stopCastDeviceDiscovery successfully');
1258  }
1259});
1260```
1261
1262## avSession.stopCastDeviceDiscovery<sup>10+</sup>
1263
1264stopCastDeviceDiscovery(): Promise\<void>
1265
1266Stops cast-enabled device discovery. This API uses a promise to return the result.
1267
1268**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1269
1270**System API**: This is a system API.
1271
1272**Return value**
1273
1274| Type          | Description                         |
1275| -------------- | ----------------------------- |
1276| Promise\<void> | Promise used to return the result. If device discovery stops, no value is returned; otherwise, an error object is returned.|
1277
1278**Example**
1279
1280```ts
1281import { BusinessError } from '@kit.BasicServicesKit';
1282
1283avSession.stopCastDeviceDiscovery().then(() => {
1284  console.info('stopCastDeviceDiscovery successfully');
1285}).catch((err: BusinessError) => {
1286  console.error(`stopCastDeviceDiscovery BusinessError: code: ${err.code}, message: ${err.message}`);
1287});
1288```
1289
1290## avSession.setDiscoverable<sup>10+</sup>
1291
1292setDiscoverable(enable: boolean, callback: AsyncCallback\<void>): void
1293
1294Sets 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.
1295
1296**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1297
1298**System API**: This is a system API.
1299
1300**Parameters**
1301
1302| Name  | Type                                 | Mandatory| Description                                 |
1303| -------- | ------------------------------------- | ---- | ------------------------------------- |
1304| enable | boolean | Yes| Whether to allow the device discoverable. The value **true** means to allow the device discoverable, and **false** means the opposite.|
1305| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.|
1306
1307**Error codes**
1308
1309For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1310
1311| ID| Error Message|
1312| -------- | ---------------------------------------- |
1313| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
1314
1315**Example**
1316
1317```ts
1318import { BusinessError } from '@kit.BasicServicesKit';
1319
1320avSession.setDiscoverable(true, (err: BusinessError) => {
1321  if (err) {
1322    console.error(`setDiscoverable BusinessError: code: ${err.code}, message: ${err.message}`);
1323  } else {
1324    console.info('setDiscoverable successfully');
1325  }
1326});
1327```
1328
1329## avSession.setDiscoverable<sup>10+</sup>
1330
1331setDiscoverable(enable: boolean): Promise\<void>
1332
1333Sets 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.
1334
1335**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1336
1337**System API**: This is a system API.
1338
1339**Parameters**
1340
1341| Name  | Type                                 | Mandatory| Description                                 |
1342| -------- | ------------------------------------- | ---- | ------------------------------------- |
1343| enable | boolean | Yes| Whether to allow the device discoverable. The value **true** means to allow the device discoverable, and **false** means the opposite.|
1344
1345**Error codes**
1346
1347For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1348
1349| ID| Error Message|
1350| -------- | ---------------------------------------- |
1351| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
1352
1353**Return value**
1354
1355| Type          | Description                         |
1356| -------------- | ----------------------------- |
1357| Promise\<void> | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.|
1358
1359**Example**
1360
1361```ts
1362import { BusinessError } from '@kit.BasicServicesKit';
1363
1364avSession.setDiscoverable(true).then(() => {
1365  console.info('setDiscoverable successfully');
1366}).catch((err: BusinessError) => {
1367  console.error(`setDiscoverable BusinessError: code: ${err.code}, message: ${err.message}`);
1368});
1369```
1370
1371## avSession.on('deviceAvailable')<sup>10+</sup>
1372
1373on(type: 'deviceAvailable', callback: (device: OutputDeviceInfo) => void): void
1374
1375Subscribes to device discovery events.
1376
1377**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1378
1379**System API**: This is a system API.
1380
1381**Parameters**
1382
1383| Name  | Type                | Mandatory| Description                                                        |
1384| -------- | -------------------- | ---- | ------------------------------------------------------------ |
1385| type     | string               | Yes  | Event type. The event **'deviceAvailable'** is triggered when a device is discovered.|
1386| callback | (device: [OutputDeviceInfo](js-apis-avsession.md#outputdeviceinfo10)) => void | Yes  | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object.                               |
1387
1388**Error codes**
1389
1390For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1391
1392| ID| Error Message|
1393| -------- | ---------------------------------------- |
1394| 201 | permission denied. |
1395| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1396
1397**Example**
1398
1399```ts
1400let castDevice: avSession.OutputDeviceInfo;
1401avSession.on('deviceAvailable', (device: avSession.OutputDeviceInfo) => {
1402  castDevice = device;
1403  console.info(`on deviceAvailable  : ${device} `);
1404});
1405```
1406
1407## avSession.off('deviceAvailable')<sup>10+</sup>
1408
1409off(type: 'deviceAvailable', callback?: (device: OutputDeviceInfo) => void): void
1410
1411Unsubscribes from device discovery events.
1412
1413**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1414
1415**System API**: This is a system API.
1416
1417**Parameters**
1418
1419| Name   | Type                   | Mandatory |      Description                                              |
1420| ------   | ---------------------- | ---- | ------------------------------------------------------- |
1421| type     | string                 | Yes   | Event type. The event **'deviceAvailable'** is triggered when a device is discovered.|
1422| callback     | (device: [OutputDeviceInfo](js-apis-avsession.md#outputdeviceinfo10)) => void                 | No   | Callback used to return the device information.|
1423
1424**Error codes**
1425
1426For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1427
1428| ID| Error Message|
1429| -------- | ---------------------------------------- |
1430| 201 | permission denied. |
1431| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1432
1433**Example**
1434
1435```ts
1436avSession.off('deviceAvailable');
1437```
1438
1439## avSession.on('deviceOffline')<sup>11+</sup>
1440
1441on(type: 'deviceOffline', callback: (deviceId: string) => void): void
1442
1443Subscribes to device offline events.
1444
1445**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1446
1447**System API**: This is a system API.
1448
1449**Parameters**
1450
1451| Name  | Type                | Mandatory| Description                                                        |
1452| -------- | -------------------- | ---- | ------------------------------------------------------------ |
1453| type     | string               | Yes  | Event type. The event **'deviceOffline'** is triggered when a device gets offline.|
1454| 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. |
1455
1456**Error codes**
1457
1458For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1459
1460| ID| Error Message|
1461| -------- | ---------------------------------------- |
1462| 201 | permission denied. |
1463| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1464
1465**Example**
1466
1467```ts
1468let castDeviceId: string;
1469avSession.on('deviceOffline', (deviceId: string) => {
1470  castDeviceId = deviceId;
1471  console.info(`on deviceOffline  : ${deviceId} `);
1472});
1473```
1474
1475## avSession.off('deviceOffline')<sup>11+</sup>
1476
1477off(type: 'deviceOffline', callback?: (deviceId: string) => void): void
1478
1479Unsubscribes from device offline events.
1480
1481**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
1482
1483**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1484
1485**System API**: This is a system API.
1486
1487**Parameters**
1488
1489| Name   | Type                   | Mandatory |      Description                                              |
1490| ------   | ---------------------- | ---- | ------------------------------------------------------- |
1491| type     | string                 | Yes   | Event type, which is **'deviceOffline'** in this case.|
1492| 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.|
1493
1494**Error codes**
1495
1496For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1497
1498| ID| Error Message|
1499| -------- | ---------------------------------------- |
1500| 201 | permission denied. |
1501| 202 | Not System App. |
1502| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1503
1504**Example**
1505
1506```ts
1507avSession.off('deviceOffline');
1508```
1509
1510## avSession.getAVCastController<sup>10+</sup>
1511
1512getAVCastController(sessionId: string, callback: AsyncCallback\<AVCastController>): void
1513
1514Obtains the cast controller when a casting connection is set up. This API uses an asynchronous callback to return the result.
1515
1516This 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.
1517
1518**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1519
1520**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
1521
1522**System API**: This is a system API.
1523
1524**Parameters**
1525
1526| Name   | Type                                                       | Mandatory| Description                                                        |
1527| --------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
1528| sessionId | string                    | Yes  |Session ID.|
1529| callback  | AsyncCallback<[AVCastController](#avcastcontroller10)\> | Yes  | Callback used to return the cast controller.|
1530
1531**Error codes**
1532
1533For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1534
1535| ID| Error Message|
1536| -------- | ---------------------------------------- |
1537| 201 | permission denied. |
1538| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
1539| 6600101  | Session service exception |
1540| 6600102  | session does not exist |
1541
1542**Example**
1543
1544```ts
1545import { BusinessError } from '@kit.BasicServicesKit';
1546
1547let currentAVSession: avSession.AVSession | undefined = undefined;
1548let tag = "createNewSession";
1549let context: Context = getContext(this);
1550let sessionId: string = "";  // Used as an input parameter of subsequent functions.
1551
1552let aVCastController: avSession.AVCastController;
1553avSession.getAVCastController(sessionId , (err: BusinessError, avcontroller: avSession.AVCastController) => {
1554  if (err) {
1555    console.error(`getAVCastController BusinessError: code: ${err.code}, message: ${err.message}`);
1556  } else {
1557    aVCastController = avcontroller;
1558    console.info('getAVCastController : SUCCESS ');
1559  }
1560});
1561```
1562
1563## avSession.getAVCastController<sup>10+</sup>
1564
1565getAVCastController(sessionId: string): Promise\<AVCastController>
1566
1567Obtains the cast controller when a casting connection is set up. This API uses a promise to return the result.
1568
1569This 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.
1570
1571**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1572
1573**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES
1574
1575**System API**: This is a system API.
1576
1577**Parameters**
1578
1579| Name   | Type                      | Mandatory| Description                                                        |
1580| --------- | ------------------------- | ---- | ------------------------------------------------------------ |
1581| sessionId | string                    | Yes  |Session ID.|
1582
1583**Return value**
1584
1585| Type                                                       | Description            |
1586| --------- | ------------------------------------------------------------ |
1587| Promise<[AVCastController](#avcastcontroller10)\>  | Promise used to return the cast controller.|
1588
1589**Error codes**
1590
1591For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1592
1593| ID| Error Message|
1594| -------- | ---------------------------------------- |
1595| 201 | permission denied. |
1596| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
1597| 6600101  | server exception |
1598| 6600102  | The session does not exist |
1599
1600**Example**
1601
1602```ts
1603import { BusinessError } from '@kit.BasicServicesKit';
1604
1605let currentAVSession: avSession.AVSession | undefined = undefined;
1606let tag = "createNewSession";
1607let context: Context = getContext(this);
1608let sessionId: string = "";  // Used as an input parameter of subsequent functions.
1609
1610let aVCastController: avSession.AVCastController;
1611avSession.getAVCastController(sessionId).then((avcontroller: avSession.AVCastController) => {
1612  aVCastController = avcontroller;
1613  console.info('getAVCastController : SUCCESS');
1614}).catch((err: BusinessError) => {
1615  console.error(`getAVCastController BusinessError: code: ${err.code}, message: ${err.message}`);
1616});
1617```
1618
1619## avSession.startCasting<sup>10+</sup>
1620
1621startCasting(session: SessionToken, device: OutputDeviceInfo, callback: AsyncCallback\<void>): void
1622
1623Starts casting. This API uses an asynchronous callback to return the result.
1624
1625**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
1626
1627**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1628
1629**System API**: This is a system API.
1630
1631**Parameters**
1632
1633| Name  | Type                                 | Mandatory| Description                                 |
1634| -------- | ------------------------------------- | ---- | ------------------------------------- |
1635| session      | [SessionToken](#sessiontoken) | Yes  | Session token.  |
1636| device | [OutputDeviceInfo](js-apis-avsession.md#outputdeviceinfo10)                        | Yes  | Device-related information.|
1637| 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.|
1638
1639**Error codes**
1640
1641For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1642
1643| ID| Error Message|
1644| -------- | ---------------------------------------- |
1645| 201 | permission denied. |
1646| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
1647| 6600101  | Session service exception. |
1648| 6600108 | Device connection failed.       |
1649
1650**Example**
1651
1652```ts
1653import { BusinessError } from '@kit.BasicServicesKit';
1654
1655let myToken: avSession.SessionToken = {
1656  sessionId: sessionId,
1657}
1658let castDevice: avSession.OutputDeviceInfo | undefined = undefined;
1659avSession.on('deviceAvailable', (device: avSession.OutputDeviceInfo) => {
1660  castDevice = device;
1661  console.info(`on deviceAvailable  : ${device} `);
1662});
1663if (castDevice !== undefined) {
1664  avSession.startCasting(myToken, castDevice, (err: BusinessError) => {
1665    if (err) {
1666      console.error(`startCasting BusinessError: code: ${err.code}, message: ${err.message}`);
1667    } else {
1668      console.info('startCasting successfully');
1669    }
1670  });
1671}
1672```
1673
1674
1675## avSession.startCasting<sup>10+</sup>
1676
1677startCasting(session: SessionToken, device: OutputDeviceInfo): Promise\<void>
1678
1679Starts casting. This API uses a promise to return the result.
1680
1681**Required permissions**: ohos.permission.MANAGE_MEDIA_RESOURCES (available only to system applications)
1682
1683**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1684
1685**System API**: This is a system API.
1686
1687**Parameters**
1688
1689| Name  | Type                                 | Mandatory| Description                                 |
1690| -------- | ------------------------------------- | ---- | ------------------------------------- |
1691| session      | [SessionToken](#sessiontoken) | Yes  | Session token.  |
1692| device | [OutputDeviceInfo](js-apis-avsession.md#outputdeviceinfo10)                        | Yes  | Device-related information.|
1693
1694**Return value**
1695
1696| Type          | Description                         |
1697| -------------- | ----------------------------- |
1698| 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.|
1699
1700**Error codes**
1701
1702For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1703
1704| ID| Error Message|
1705| -------- | ---------------------------------------- |
1706| 201 | permission denied. |
1707| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
1708| 6600101  | Session service exception. |
1709| 6600108 | Device connection failed.       |
1710
1711**Example**
1712
1713```ts
1714import { BusinessError } from '@kit.BasicServicesKit';
1715
1716let myToken: avSession.SessionToken = {
1717  sessionId: sessionId,
1718}
1719let castDevice: avSession.OutputDeviceInfo | undefined = undefined;
1720avSession.on('deviceAvailable', (device: avSession.OutputDeviceInfo) => {
1721  castDevice = device;
1722  console.info(`on deviceAvailable  : ${device} `);
1723});
1724if (castDevice !== undefined) {
1725  avSession.startCasting(myToken, castDevice).then(() => {
1726    console.info('startCasting successfully');
1727  }).catch((err: BusinessError) => {
1728    console.error(`startCasting BusinessError: code: ${err.code}, message: ${err.message}`);
1729  });
1730}
1731```
1732
1733## avSession.stopCasting<sup>10+</sup>
1734
1735stopCasting(session: SessionToken, callback: AsyncCallback\<void>): void
1736
1737Stops castings. This API uses an asynchronous callback to return the result.
1738
1739**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1740
1741**System API**: This is a system API.
1742
1743**Parameters**
1744
1745| Name  | Type                                 | Mandatory| Description                                 |
1746| -------- | ------------------------------------- | ---- | ------------------------------------- |
1747| session      | [SessionToken](#sessiontoken) | Yes  | Session token.  |
1748| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If casting stops, **err** is **undefined**; otherwise, **err** is an error object.|
1749
1750**Error codes**
1751
1752For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1753
1754| ID| Error Message|
1755| -------- | ---------------------------------------- |
1756| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
1757| 6600109  | The remote connection is not established. |
1758
1759**Example**
1760
1761```ts
1762import { BusinessError } from '@kit.BasicServicesKit';
1763
1764let myToken: avSession.SessionToken = {
1765  sessionId: sessionId,
1766}
1767avSession.stopCasting(myToken, (err: BusinessError) => {
1768  if (err) {
1769    console.error(`stopCasting BusinessError: code: ${err.code}, message: ${err.message}`);
1770  } else {
1771    console.info('stopCasting successfully');
1772  }
1773});
1774```
1775
1776## avSession.stopCasting<sup>10+</sup>
1777
1778stopCasting(session: SessionToken): Promise\<void>
1779
1780Stops castings. This API uses a promise to return the result.
1781
1782**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1783
1784**System API**: This is a system API.
1785
1786**Parameters**
1787
1788| Name  | Type                                 | Mandatory| Description                                 |
1789| -------- | ------------------------------------- | ---- | ------------------------------------- |
1790| session      | [SessionToken](#sessiontoken) | Yes  | Session token.  |
1791
1792**Return value**
1793
1794| Type          | Description                         |
1795| -------------- | ----------------------------- |
1796| Promise\<void> | Promise used to return the result. If casting stops, no value is returned; otherwise, an error object is returned.|
1797
1798**Error codes**
1799
1800For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1801
1802| ID| Error Message|
1803| -------- | ---------------------------------------- |
1804| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
1805| 6600109  | The remote connection is not established. |
1806
1807**Example**
1808
1809```ts
1810import { BusinessError } from '@kit.BasicServicesKit';
1811
1812let myToken: avSession.SessionToken = {
1813  sessionId: sessionId,
1814}
1815avSession.stopCasting(myToken).then(() => {
1816  console.info('stopCasting successfully');
1817}).catch((err: BusinessError) => {
1818  console.error(`stopCasting BusinessError: code: ${err.code}, message: ${err.message}`);
1819});
1820```
1821
1822## avSession.startDeviceLogging<sup>13+</sup>
1823
1824startDeviceLogging(url: string, maxSize?: number): Promise\<void>
1825
1826Starts to write device logs to a file. This API uses a promise to return the result.
1827
1828**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1829
1830**System API**: This is a system API.
1831
1832**Parameters**
1833
1834| Name  | Type                                 | Mandatory| Description                                 |
1835| -------- | ------------------------------------- | ---- | ------------------------------------- |
1836| url | string                   | Yes  | Target file descriptor (unique identifier used to open a file).|
1837| maxSize | number                   | No  | Maximum size of the log file, in KB.|
1838
1839**Return value**
1840
1841| Type          | Description                         |
1842| -------------- | ----------------------------- |
1843| Promise\<void> | Promise used to return the result. If the device logs are written to the file successfully, no result is returned; otherwise, an error object is returned.|
1844
1845**Error codes**
1846
1847For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1848
1849| ID| Error Message|
1850| -------- | ---------------------------------------- |
1851| 202        | Not System App. |
1852| 401        | Parameter check failed. 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types.|
1853| 6600101    | Session service exception. |
1854| 6600102    | The session does not exist. |
1855
1856**Example**
1857
1858```ts
1859import { BusinessError } from '@kit.BasicServicesKit';
1860import { fileIo } from '@kit.CoreFileKit';
1861
1862let file = await fileIo.open("filePath");
1863let url = file.fd.toString();
1864avSession.startDeviceLogging(url, 2048).then(() => {
1865  console.info('startDeviceLogging successfully');
1866}).catch((err: BusinessError) => {
1867  console.error(`startDeviceLogging BusinessError: code: ${err.code}, message: ${err.message}`);
1868})
1869```
1870
1871## avSession.stopDeviceLogging<sup>13+</sup>
1872
1873stopDeviceLogging(): Promise\<void>
1874
1875Stops device logging. This API uses a promise to return the result.
1876
1877**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1878
1879**System API**: This is a system API.
1880
1881**Return value**
1882
1883| Type          | Description                         |
1884| -------------- | ----------------------------- |
1885| Promise\<void> | Promise used to return the result. If device logging is stopped, no result is returned; otherwise, an error object is returned.|
1886
1887**Error codes**
1888
1889For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1890
1891| ID| Error Message|
1892| -------- | ---------------------------------------- |
1893| 202        | Not System App. |
1894| 6600101    | Session service exception. |
1895| 6600102    | The session does not exist. |
1896
1897**Example**
1898
1899```ts
1900import { BusinessError } from '@kit.BasicServicesKit';
1901
1902avSession.stopDeviceLogging().then(() => {
1903  console.info('stopCasting successfully');
1904}).catch((err: BusinessError) => {
1905  console.error(`stopCasting BusinessError: code: ${err.code}, message: ${err.message}`);
1906});
1907```
1908
1909## avSession.on('deviceLogEvent')<sup>13+</sup>
1910
1911on(type: 'deviceLogEvent', callback: Callback\<DeviceLogEventCode>): void
1912
1913Subscribes to device log events.
1914
1915**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1916
1917**System API**: This is a system API.
1918
1919**Parameters**
1920
1921| Name  | Type                                                        | Mandatory| Description                                                        |
1922| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
1923| type     | string                                                       | Yes  | Event type, which is **'deviceLogEvent'** in this case.|
1924| callback | (callback: [DeviceLogEventCode](#devicelogeventcode13)) => void        | Yes  | Callback function, in which **DeviceLogEventCode** is the return value of the current device log event.                     |
1925
1926**Error codes**
1927
1928For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1929
1930| ID| Error Message|
1931| -------- | ---------------------------------------- |
1932| 202        | Not System App. |
1933| 401        | Parameter check failed. 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types.|
1934| 6600101    | Session service exception. |
1935| 6600102    | The session does not exist. |
1936
1937**Example**
1938
1939```ts
1940avSession.on('deviceLogEvent', (eventCode: avSession.DeviceLogEventCode) => {
1941  console.info(`on deviceLogEvent code : ${eventCode}`);
1942});
1943```
1944
1945## avSession.off('deviceLogEvent')<sup>13+</sup>
1946
1947off(type: 'deviceLogEvent', callback?: Callback\<DeviceLogEventCode>): void
1948
1949Unsubscribes from device log events.
1950
1951**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1952
1953**System API**: This is a system API.
1954
1955**Parameters**
1956
1957| Name  | Type                                                        | Mandatory| Description                                                        |
1958| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
1959| type     | string                                                       | Yes  | Event type, which is **'deviceLogEvent'** in this case.|
1960| callback | (callback: [DeviceLogEventCode](#devicelogeventcode13)) => void        | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object. The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.           |
1961
1962**Error codes**
1963
1964For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
1965
1966| ID| Error Message|
1967| -------- | ---------------------------------------- |
1968| 202        | Not System App. |
1969| 401        | Parameter check failed. 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types.|
1970| 6600101    | Session service exception. |
1971| 6600102    | The session does not exist. |
1972
1973**Example**
1974
1975```ts
1976avSession.off('deviceLogEvent');
1977```
1978
1979## AVCastController<sup>10+</sup>
1980
1981After a casting connection is set up, you can call [avSession.getAVCastController](js-apis-avsession.md#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.
1982
1983### setDisplaySurface<sup>10+</sup>
1984
1985setDisplaySurface(surfaceId: string): Promise\<void>
1986
1987Sets the surface ID for playback, which is used at the cast receiver (sink). This API uses a promise to return the result.
1988
1989**System capability**: SystemCapability.Multimedia.AVSession.AVCast
1990
1991**System API**: This is a system API.
1992
1993**Return value**
1994
1995| Type                                         | Description                       |
1996| --------------------------------------------- | --------------------------- |
1997| Promise\<void> | Promise used to return the result.|
1998
1999**Error codes**
2000
2001For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
2002
2003| ID| Error Message|
2004| -------- | ---------------------------------------- |
2005| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
2006| 6600109  | The remote connection is not established. |
2007
2008**Example**
2009
2010```ts
2011import { media } from '@kit.MediaKit';
2012let surfaceID: string = '';
2013media.createAVRecorder().then((avRecorder) => {
2014  avRecorder.getInputSurface((err: BusinessError, surfaceId: string) => {
2015    if (err == null) {
2016      console.info('getInputSurface success');
2017      surfaceID = surfaceId;
2018    } else {
2019      console.error('getInputSurface failed and error is ' + err.message);
2020    }
2021  });
2022})
2023aVCastController.setDisplaySurface(surfaceID).then(() => {
2024  console.info('setDisplaySurface : SUCCESS');
2025});
2026```
2027
2028### setDisplaySurface<sup>10+</sup>
2029
2030setDisplaySurface(surfaceId: string, callback: AsyncCallback\<void>): void
2031
2032Sets the surface ID for playback, which is used at the cast receiver (sink). This API uses an asynchronous callback to return the result.
2033
2034**System capability**: SystemCapability.Multimedia.AVSession.AVCast
2035
2036**System API**: This is a system API.
2037
2038**Parameters**
2039
2040| Name  | Type                                               | Mandatory| Description                        |
2041| -------- | --------------------------------------------------- | ---- | ---------------------------- |
2042| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
2043| surfaceId | string | Yes  | Surface ID.|
2044
2045
2046**Error codes**
2047
2048For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
2049
2050| ID| Error Message|
2051| -------- | ---------------------------------------- |
2052| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Parameter verification failed. |
2053| 6600109  | The remote connection is not established. |
2054
2055**Example**
2056
2057```ts
2058import { BusinessError } from '@kit.BasicServicesKit';
2059import { media } from '@kit.MediaKit';
2060let surfaceID: string = '';
2061media.createAVRecorder().then((avRecorder) => {
2062  avRecorder.getInputSurface((err: BusinessError, surfaceId: string) => {
2063    if (err == null) {
2064      console.info('getInputSurface success');
2065      surfaceID = surfaceId;
2066    } else {
2067      console.error('getInputSurface failed and error is ' + err.message);
2068    }
2069  });
2070})
2071aVCastController.setDisplaySurface(surfaceID, (err: BusinessError) => {
2072  if (err) {
2073    console.error(`setDisplaySurface BusinessError: code: ${err.code}, message: ${err.message}`);
2074  } else {
2075    console.info('setDisplaySurface : SUCCESS');
2076  }
2077});
2078```
2079
2080### on('videoSizeChange')<sup>10+</sup>
2081
2082on(type: 'videoSizeChange', callback: (width:number, height:number) => void): void
2083
2084Subscribes to video size change events.
2085
2086**System capability**: SystemCapability.Multimedia.AVSession.AVCast
2087
2088**System API**: This is a system API.
2089
2090**Parameters**
2091
2092| Name  | Type        | Mandatory| Description                                                        |
2093| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
2094| type     | string      | Yes  | Event type. The event **'videoSizeChange'** is triggered when the video size changes.|
2095| callback | (width:number, height:number) => void    | Yes  | Callback used to return the video width and height.    |
2096
2097**Error codes**
2098
2099For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
2100
2101| ID| Error Message|
2102| -------- | ---------------- |
2103| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
2104| 6600101  | Session service exception. |
2105
2106**Example**
2107
2108```ts
2109aVCastController.on('videoSizeChange', (width: number, height: number) => {
2110  console.info(`width : ${width} `);
2111  console.info(`height: ${height} `);
2112});
2113```
2114
2115### off('videoSizeChange')<sup>10+</sup>
2116
2117off(type: 'videoSizeChange'): void
2118
2119Unsubscribes from video size changes.
2120
2121**System capability**: SystemCapability.Multimedia.AVSession.AVCast
2122
2123**System API**: This is a system API.
2124
2125**Parameters**
2126
2127| Name  | Type    | Mandatory| Description     |
2128| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
2129| type     | string  | Yes  | Event type, which is **'videoSizeChange'** in this case.   |
2130
2131**Error codes**
2132
2133For details about the error codes, see [AVSession Management Error Codes](errorcode-avsession.md).
2134
2135| ID| Error Message|
2136| -------- | ---------------- |
2137| 401 |  parameter check failed. 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
2138| 6600101  | Session service exception. |
2139
2140**Example**
2141
2142```ts
2143aVCastController.off('videoSizeChange');
2144```
2145
2146## AVMetadata<sup>10+</sup>
2147
2148Describes the media metadata.
2149
2150**System capability**: SystemCapability.Multimedia.AVSession.Core
2151
2152| Name           | Type                     | Mandatory| Description                                                                 |
2153| --------------- |-------------------------| ---- |---------------------------------------------------------------------|
2154| avQueueName<sup>11+</sup>     | string                  | No  | Playlist name.<br>This is a system API.|
2155
2156## AVQueueInfo<sup>11+</sup>
2157
2158Defines the attributes of a playlist.
2159
2160**System capability**: SystemCapability.Multimedia.AVSession.Core
2161
2162**System API**: This is a system API.
2163
2164| Name           | Type                     | Mandatory| Description                                                                 |
2165| --------------- |-------------------------| ---- |--------------------------------------------------------------------- |
2166| bundleName      | string                  | Yes  | Bundle name of the application to which the playlist belongs.                                                       |
2167| avQueueName     | string                  | Yes  | Playlist name.                                                   |
2168| avQueueId       | string                  | Yes  | Unique ID of the playlist.                                              |
2169| avQueueImage    | image.PixelMap &#124; string |Yes  | Cover image of the playlist, which can be pixel data of an image or an image path (local path or Internet path).    |
2170| lastPlayedTime  | number                  | No  | Last time when the playlist is played.                                                       |
2171
2172## DeviceInfo<sup>10+</sup>
2173
2174Describes the information related to the output device.
2175
2176| Name      | Type          | Mandatory| Description                  |
2177| ---------- | -------------- | ---- | ---------------------- |
2178| ipAddress | string | No  | IP address of the output device.<br>This is a system API.<br> **System capability**: SystemCapability.Multimedia.AVSession.AVCast    |
2179| providerId | number | No  | Vendor of the output device.<br>This is a system API.<br> **System capability**: SystemCapability.Multimedia.AVSession.AVCast   |
2180| authenticationStatus<sup>11+</sup> | number | No  | Whether the output device is trusted. The default value is **0**, indicating that the device is untrusted. The value **1** means that the device is trusted.<br>This is a system API.<br> **System capability**: SystemCapability.Multimedia.AVSession.AVCast   |
2181| networkId<sup>13+</sup> | string | No  | Network ID of the output device.<br>This is a system API.<br> **System capability**: SystemCapability.Multimedia.AVSession.AVCast|
2182
2183## AVSessionDescriptor
2184
2185Declares the session descriptor.
2186
2187**System capability**: SystemCapability.Multimedia.AVSession.Manager
2188
2189**System API**: This is a system API.
2190
2191| Name         | Type             | Readable| Writable| Description |
2192| --------------| ---------------- | ---------------- | ---------------- |------|
2193| sessionId    | string    | Yes| Yes | Session ID.     |
2194| type         | [AVSessionType](js-apis-avsession.md#avsessiontype10)   | Yes| Yes| Session type.   |
2195| sessionTag   | string             | Yes| Yes| Custom session name.   |
2196| elementName  | [ElementName](../apis-ability-kit/js-apis-bundle-ElementName.md)  | Yes| Yes| Information about the application to which the session belongs, including the bundle name and ability name.|
2197| isActive     | boolean             | Yes| Yes| Whether the session is activated.<br>**true**: The session is activated.<br>**false**: The service is not activated.                                     |
2198| isTopSession | boolean             | Yes| Yes| Whether the session is the top session.<br>**true**: The session is the top session.<br>**false**: The session is not the top session.               |
2199| outputDevice | [OutputDeviceInfo](js-apis-avsession.md#outputdeviceinfo10)    | Yes| Yes| Information about the output device.  |
2200
2201## DeviceLogEventCode<sup>13+</sup>
2202
2203Enumerates the return values of device log events.
2204
2205**System capability**: SystemCapability.Multimedia.AVSession.AVCast
2206
2207**System API**: This is a system API.
2208
2209| Name                       | Value  | Description        |
2210| --------------------------- | ---- | ----------- |
2211| DEVICE_LOG_FULL       | 1    | The log file is full.   |
2212| DEVICE_LOG_EXCEPTION       | 2    | An exception occurs during device logging.|
2213