1# AVSession Controller (for System Applications Only) 2 3Media Controller preset in OpenHarmony functions as the controller to interact with audio and video applications, for example, obtaining and displaying media information and delivering playback control commands. 4 5You can develop a system application (for example, a new playback control center or voice assistant) as the controller to interact with audio and video applications in the system. 6 7## Basic Concepts 8 9- AVSessionDescriptor: session information, including the session ID, session type (audio/video), custom session name (**sessionTag**), information about the corresponding application (**elementName**), and whether the session is pined on top (isTopSession). 10 11- Top session: session with the highest priority in the system, for example, a session that is being played. Generally, the controller must hold an **AVSessionController** object to communicate with a session. However, the controller can directly communicate with the top session, for example, directly sending a playback control command or key event, without holding an **AVSessionController** object. 12 13## Available APIs 14 15The key APIs used by the controller are classified into the following types: 16 171. APIs called by the **AVSessionManager** object, which is obtained by means of import. An example API is **AVSessionManager.createController(sessionId)**. 182. APIs called by the **AVSessionController** object. An example API is **controller.getAVPlaybackState()**. 19 20Asynchronous JavaScript APIs use either a callback or promise to return the result. The APIs listed below use a callback. They provide the same functions as their counterparts that use a promise. 21 22For details, see [AVSession Management](../../reference/apis-avsession-kit/js-apis-avsession.md). 23 24### APIs Called by the AVSessionManager Object 25 26| API| Description| 27| -------- | -------- | 28| getAllSessionDescriptors(callback: AsyncCallback<Array<Readonly<AVSessionDescriptor>>>): void | Obtains the descriptors of all AVSessions in the system.| 29| createController(sessionId: string, callback: AsyncCallback<AVSessionController>): void | Creates an AVSessionController.| 30| sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void | Sends a key event to the top session.| 31| sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void | Sends a playback control command to the top session.| 32| getHistoricalSessionDescriptors(maxSize: number, callback: AsyncCallback\<Array\<Readonly\<AVSessionDescriptor>>>): void<sup>10+<sup> | Obtains the descriptors of historical sessions.| 33 34### APIs Called by the AVSessionController Object 35 36| API| Description| 37| -------- | -------- | 38| getAVPlaybackState(callback: AsyncCallback<AVPlaybackState>): void<sup>10+<sup> | Obtains the information related to the playback state.| 39| getAVMetadata(callback: AsyncCallback<AVMetadata>): void<sup>10+<sup> | Obtains the session metadata.| 40| getOutputDevice(callback: AsyncCallback<OutputDeviceInfo>): void<sup>10+<sup> | Obtains the output device information.| 41| sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void<sup>10+<sup> | Sends a key event to the session corresponding to this controller.| 42| getLaunchAbility(callback: AsyncCallback<WantAgent>): void<sup>10+<sup> | Obtains the **WantAgent** object saved by the application in the session.| 43| isActive(callback: AsyncCallback<boolean>): void<sup>10+<sup> | Checks whether the session is activated.| 44| destroy(callback: AsyncCallback<void>): void<sup>10+<sup> | Destroys this controller. A controller can no longer be used after being destroyed.| 45| getValidCommands(callback: AsyncCallback<Array<AVControlCommandType>>): void<sup>10+<sup> | Obtains valid commands supported by the session.| 46| sendControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void<sup>10+<sup> | Sends a playback control command to the session through the controller.| 47| sendCommonCommand(command: string, args: {[key: string]: Object}, callback: AsyncCallback<void>): void<sup>10+<sup> | Sends a custom playback control command to the session through the controller.| 48| getAVQueueItems(callback: AsyncCallback<Array<AVQueueItem>>): void<sup>10+<sup> | Obtains the information related to the items in the playlist.| 49| getAVQueueTitle(callback: AsyncCallback<string>): void<sup>10+<sup> | Obtains the name of the playlist.| 50| skipToQueueItem(itemId: number, callback: AsyncCallback<void>): void<sup>10+<sup> | Sends the ID of an item in the playlist to the session for processing. The session can play the song.| 51| getExtras(callback: AsyncCallback<{[key: string]: Object}>): void<sup>10+<sup> | Obtains the custom media packet set by the provider.| 52| getOutputDeviceSync(): OutputDeviceInfo<sup>10+<sup> | Obtains the output device information. This API returns the result synchronously. | 53| getAVPlaybackStateSync(): AVPlaybackState<sup>10+<sup> | Obtains the information related to the playback state. This API returns the result synchronously. | 54| getAVMetadataSync(): AVMetadata<sup>10+<sup> | Obtains the session metadata. This API returns the result synchronously. | 55| getAVQueueTitleSync(): string<sup>10+<sup> | Obtains the name of the playlist. This API returns the result synchronously. | 56| getAVQueueItemsSync(): Array<AVQueueItem><sup>10+<sup> | Obtains the information related to the items in the playlist. This API returns the result synchronously. | 57| isActiveSync(): boolean<sup>10+<sup> | Checks whether the session is activated. This API returns the result synchronously.| 58| getValidCommandsSync(): Array<AVControlCommandType><sup>10+<sup> | Obtains valid commands supported by the session. This API returns the result synchronously.| 59 60## How to Develop 61 62To enable a system application to access the AVSession service as a controller, proceed as follows: 63 641. Obtain **AVSessionDescriptor** through AVSessionManager and create an **AVSessionController** object. 65 66 The controller may obtain all **AVSessionDescriptor**s in the current system, and create an **AVSessionController** object for each session, so as to perform unified playback control on all the audio and video applications. 67 68 ```ts 69 // Import the AVSessionManager module. 70 import { avSession as AVSessionManager } from '@kit.AVSessionKit'; 71 import { BusinessError } from '@kit.BasicServicesKit'; 72 73 // Define global variables. 74 let g_controller = new Array<AVSessionManager.AVSessionController>(); 75 let g_centerSupportCmd:Set<AVSessionManager.AVControlCommandType> = new Set(['play', 'pause', 'playNext', 'playPrevious', 'fastForward', 'rewind', 'seek','setSpeed', 'setLoopMode', 'toggleFavorite']); 76 let g_validCmd:Set<AVSessionManager.AVControlCommandType>; 77 // Obtain the session descriptors and create an AVSessionController object. 78 AVSessionManager.getAllSessionDescriptors().then((descriptors) => { 79 descriptors.forEach((descriptor) => { 80 AVSessionManager.createController(descriptor.sessionId).then((controller) => { 81 g_controller.push(controller); 82 }).catch((err: BusinessError) => { 83 console.error(`Failed to create controller. Code: ${err.code}, message: ${err.message}`); 84 }); 85 }); 86 }).catch((err: BusinessError) => { 87 console.error(`Failed to get all session descriptors. Code: ${err.code}, message: ${err.message}`); 88 }); 89 90 // Obtain the descriptors of historical sessions. 91 AVSessionManager.getHistoricalSessionDescriptors().then((descriptors) => { 92 console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`); 93 if (descriptors.length > 0){ 94 console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`); 95 console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`); 96 console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`); 97 console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionId : ${descriptors[0].sessionId}`); 98 console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].elementName.bundleName : ${descriptors[0].elementName.bundleName}`); 99 } 100 }).catch((err: BusinessError) => { 101 console.error(`Failed to get historical session descriptors, error code: ${err.code}, error message: ${err.message}`); 102 }); 103 ``` 104 1052. Listen for the session state and service state events. 106 107 The following session state events are available: 108 109 - **sessionCreate**: triggered when a session is created. 110 - **sessionDestroy**: triggered when a session is destroyed. 111 - **topSessionChange**: triggered when the top session is changed. 112 113 The service state event **sessionServiceDie** is reported when the AVSession service is abnormal. 114 115 ```ts 116 import { avSession as AVSessionManager } from '@kit.AVSessionKit'; 117 import { BusinessError } from '@kit.BasicServicesKit'; 118 119 let g_controller = new Array<AVSessionManager.AVSessionController>(); 120 // Subscribe to the 'sessionCreate' event and create an AVSessionController object. 121 AVSessionManager.on('sessionCreate', (session) => { 122 // After an AVSession is added, you must create an AVSessionController object. 123 AVSessionManager.createController(session.sessionId).then((controller) => { 124 g_controller.push(controller); 125 }).catch((err: BusinessError) => { 126 console.error(`Failed to create controller. Code: ${err.code}, message: ${err.message}`); 127 }); 128 }); 129 130 // Subscribe to the 'sessionDestroy' event to enable the application to get notified when the session dies. 131 AVSessionManager.on('sessionDestroy', (session) => { 132 let index = g_controller.findIndex((controller) => { 133 return controller.sessionId === session.sessionId; 134 }); 135 if (index !== 0) { 136 g_controller[index].destroy(); 137 g_controller.splice(index, 1); 138 } 139 }); 140 // Subscribe to the 'topSessionChange' event. 141 AVSessionManager.on('topSessionChange', (session) => { 142 let index = g_controller.findIndex((controller) => { 143 return controller.sessionId === session.sessionId; 144 }); 145 // Place the session on the top. 146 if (index !== 0) { 147 g_controller.sort((a, b) => { 148 return a.sessionId === session.sessionId ? -1 : 0; 149 }); 150 } 151 }); 152 // Subscribe to the 'sessionServiceDie' event. 153 AVSessionManager.on('sessionServiceDie', () => { 154 // The server is abnormal, and the application clears resources. 155 console.info(`Server exception.`); 156 }) 157 ``` 158 1593. Subscribe to media information changes and other session events. 160 161 The following media information change events are available: 162 163 - **metadataChange**: triggered when the session metadata changes. 164 - **playbackStateChange**: triggered when the playback state changes. 165 - **activeStateChange**: triggered when the activation state of the session changes. 166 - **validCommandChange**: triggered when the valid commands supported by the session changes. 167 - **outputDeviceChange**: triggered when the output device changes. 168 - **sessionDestroy**: triggered when a session is destroyed. 169 - **sessionEvent**: triggered when the custom session event changes. 170 - **extrasChange**: triggered when the custom media packet of the session changes. 171 - **queueItemsChange**: triggered when one or more items in the custom playlist of the session changes. 172 - **queueTitleChange**: triggered when the custom playlist name of the session changes. 173 174 The controller can listen for events as required. 175 176 ```ts 177 import { avSession as AVSessionManager } from '@kit.AVSessionKit'; 178 import { BusinessError } from '@kit.BasicServicesKit'; 179 180 let g_controller = new Array<AVSessionManager.AVSessionController>(); 181 let controller = g_controller[0]; 182 let g_validCmd:Set<AVSessionManager.AVControlCommandType>; 183 let g_centerSupportCmd:Set<AVSessionManager.AVControlCommandType> = new Set(['play', 'pause', 'playNext', 'playPrevious', 'fastForward', 'rewind', 'seek','setSpeed', 'setLoopMode', 'toggleFavorite']); 184 // Subscribe to the 'activeStateChange' event. 185 controller.on('activeStateChange', (isActive) => { 186 if (isActive) { 187 console.info(`The widget corresponding to the controller is highlighted.`); 188 } else { 189 console.info(`The widget corresponding to the controller is invalid.`); 190 } 191 }); 192 // Subscribe to the 'sessionDestroy' event to enable the controller to get notified when the session dies. 193 controller.on('sessionDestroy', () => { 194 console.info(`on sessionDestroy : SUCCESS `); 195 controller.destroy().then(() => { 196 console.info(`destroy : SUCCESS`); 197 }).catch((err: BusinessError) => { 198 console.error(`Failed to destroy session. Code: ${err.code}, message: ${err.message}`); 199 }); 200 }); 201 202 // Subscribe to metadata changes. 203 controller.on('metadataChange', ['assetId', 'title', 'description'], (metadata: AVSessionManager.AVMetadata) => { 204 console.info(`on metadataChange assetId : ${metadata.assetId}`); 205 }); 206 // Subscribe to playback state changes. 207 controller.on('playbackStateChange', ['state', 'speed', 'loopMode'], (playbackState: AVSessionManager.AVPlaybackState) => { 208 console.info(`on playbackStateChange state : ${playbackState.state}`); 209 }); 210 // Subscribe to supported command changes. 211 controller.on('validCommandChange', (cmds) => { 212 console.info(`validCommandChange : SUCCESS : size : ${cmds.length}`); 213 console.info(`validCommandChange : SUCCESS : cmds : ${cmds.values()}`); 214 g_validCmd.clear(); 215 let centerSupportCmd = Array.from(g_centerSupportCmd.values()) 216 for (let c of centerSupportCmd) { 217 if (cmds.concat(c)) { 218 g_validCmd.add(c); 219 } 220 } 221 }); 222 // Subscribe to output device changes. 223 controller.on('outputDeviceChange', (state, device) => { 224 console.info(`outputDeviceChange device are : ${JSON.stringify(device)}`); 225 }); 226 // Subscribe to custom session event changes. 227 controller.on('sessionEvent', (eventName, eventArgs) => { 228 console.info(`Received new session event, event name is ${eventName}, args are ${JSON.stringify(eventArgs)}`); 229 }); 230 // Subscribe to custom media packet changes. 231 controller.on('extrasChange', (extras) => { 232 console.info(`Received custom media packet, packet data is ${JSON.stringify(extras)}`); 233 }); 234 // Subscribe to custom playlist item changes. 235 controller.on('queueItemsChange', (items) => { 236 console.info(`Caught queue items change, items length is ${items.length}`); 237 }); 238 // Subscribe to custom playback name changes. 239 controller.on('queueTitleChange', (title) => { 240 console.info(`Caught queue title change, title is ${title}`); 241 }); 242 ``` 243 2444. Obtain the media information transferred by the provider for display on the UI, for example, displaying the track being played and the playback state in Media Controller. 245 246 ```ts 247 import { avSession as AVSessionManager } from '@kit.AVSessionKit'; 248 async function getInfoFromSessionByController() { 249 // It is assumed that an AVSessionController object corresponding to the session already exists. For details about how to create an AVSessionController object, see the code snippet above. 250 let controller = await AVSessionManager.createController("") 251 // Obtain the session ID. 252 let sessionId = controller.sessionId; 253 console.info(`get sessionId by controller : isActive : ${sessionId}`); 254 // Obtain the activation state of the session. 255 let isActive = await controller.isActive(); 256 console.info(`get activeState by controller : ${isActive}`); 257 // Obtain the media information of the session. 258 let metadata = await controller.getAVMetadata(); 259 console.info(`get media title by controller : ${metadata.title}`); 260 console.info(`get media artist by controller : ${metadata.artist}`); 261 // Obtain the playback information of the session. 262 let avPlaybackState = await controller.getAVPlaybackState(); 263 console.info(`get playbackState by controller : ${avPlaybackState.state}`); 264 console.info(`get favoriteState by controller : ${avPlaybackState.isFavorite}`); 265 // Obtain the playlist items of the session. 266 let queueItems = await controller.getAVQueueItems(); 267 console.info(`get queueItems length by controller : ${queueItems.length}`); 268 // Obtain the playlist name of the session. 269 let queueTitle = await controller.getAVQueueTitle(); 270 console.info(`get queueTitle by controller : ${queueTitle}`); 271 // Obtain the custom media packet of the session. 272 let extras = await controller.getExtras(); 273 console.info(`get custom media packets by controller : ${JSON.stringify(extras)}`); 274 // Obtain the ability information provided by the application corresponding to the session. 275 let agent = await controller.getLaunchAbility(); 276 console.info(`get want agent info by controller : ${JSON.stringify(agent)}`); 277 // Obtain the current playback position of the session. 278 let currentTime = controller.getRealPlaybackPositionSync(); 279 console.info(`get current playback time by controller : ${currentTime}`); 280 // Obtain valid commands supported by the session. 281 let validCommands = await controller.getValidCommands(); 282 console.info(`get valid commands by controller : ${JSON.stringify(validCommands)}`); 283 } 284 ``` 285 2865. Control the playback behavior, for example, sending a command to operate (play/pause/previous/next) the item being played in Media Controller. 287 288 After listening for the playback control command event, the audio and video application serving as the provider needs to implement the corresponding operation. 289 290 ```ts 291 import { avSession as AVSessionManager } from '@kit.AVSessionKit'; 292 import { BusinessError } from '@kit.BasicServicesKit'; 293 294 async function sendCommandToSessionByController() { 295 // It is assumed that an AVSessionController object corresponding to the session already exists. For details about how to create an AVSessionController object, see the code snippet above. 296 let controller = await AVSessionManager.createController("") 297 // Obtain valid commands supported by the session. 298 let validCommandTypeArray = await controller.getValidCommands(); 299 console.info(`get validCommandArray by controller : length : ${validCommandTypeArray.length}`); 300 // Deliver the 'play' command. 301 // If the 'play' command is valid, deliver it. Normal sessions should provide and implement the playback. 302 if (validCommandTypeArray.indexOf('play') >= 0) { 303 let avCommand: AVSessionManager.AVControlCommand = {command:'play'}; 304 controller.sendControlCommand(avCommand); 305 } 306 // Deliver the 'pause' command. 307 if (validCommandTypeArray.indexOf('pause') >= 0) { 308 let avCommand: AVSessionManager.AVControlCommand = {command:'pause'}; 309 controller.sendControlCommand(avCommand); 310 } 311 // Deliver the 'playPrevious' command. 312 if (validCommandTypeArray.indexOf('playPrevious') >= 0) { 313 let avCommand: AVSessionManager.AVControlCommand = {command:'playPrevious'}; 314 controller.sendControlCommand(avCommand); 315 } 316 // Deliver the 'playNext' command. 317 if (validCommandTypeArray.indexOf('playNext') >= 0) { 318 let avCommand: AVSessionManager.AVControlCommand = {command:'playNext'}; 319 controller.sendControlCommand(avCommand); 320 } 321 // Deliver a custom playback control command. 322 let commandName = 'custom command'; 323 await controller.sendCommonCommand(commandName, {command : 'This is my custom command'}).then(() => { 324 console.info(`SendCommonCommand successfully`); 325 }).catch((err: BusinessError) => { 326 console.error(`Failed to send common command. Code: ${err.code}, message: ${err.message}`); 327 }) 328 // Set the ID of an item in the specified playlist for the session to play. 329 let queueItemId = 0; 330 await controller.skipToQueueItem(queueItemId).then(() => { 331 console.info(`SkipToQueueItem successfully`); 332 }).catch((err: BusinessError) => { 333 console.error(`Failed to skip to queue item. Code: ${err.code}, message: ${err.message}`); 334 }); 335 } 336 ``` 337 3386. When the audio and video application exits, cancel the listener and release the resources. 339 340 ```ts 341 import { avSession as AVSessionManager } from '@kit.AVSessionKit'; 342 import { BusinessError } from '@kit.BasicServicesKit'; 343 344 async function destroyController() { 345 // It is assumed that an AVSessionController object corresponding to the session already exists. For details about how to create an AVSessionController object, see the code snippet above. 346 let controller = await AVSessionManager.createController("") 347 348 // Destroy the AVSessionController object. After being destroyed, it is no longer available. 349 controller.destroy((err: BusinessError) => { 350 if (err) { 351 console.error(`Failed to destroy controller. Code: ${err.code}, message: ${err.message}`); 352 } else { 353 console.info(`Destroy controller SUCCESS`); 354 } 355 }); 356 } 357 ``` 358