• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# AVSession Provider
2
3An audio and video application needs to access the AVSession service as a provider in order to display media information in the controller (for example, Media Controller) and respond to control commands delivered by the controller.
4
5## Basic Concepts
6
7- AVMetadata: media data related attributes, including the IDs of the current media asset (assetId), previous media asset (previousAssetId), and next media asset (nextAssetId), title, author, album, writer, and duration.
8
9- AVPlaybackState: playback state attributes, including the playback state, position, speed, buffered time, loop mode, and whether the media asset is favorited (**isFavorite**).
10
11## Available APIs
12
13The table below lists the key APIs used by the provider. The 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.
14
15For details, see [AVSession Management](../reference/apis/js-apis-avsession.md).
16
17| API| Description|
18| -------- | -------- |
19| createAVSession(context: Context, tag: string, type: AVSessionType, callback: AsyncCallback&lt;AVSession&gt;): void | Creates an AVSession.<br>Only one AVSession can be created for a UIAbility.|
20| setAVMetadata(data: AVMetadata, callback: AsyncCallback&lt;void&gt;): void | Sets AVSession metadata.|
21| setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback&lt;void&gt;): void | Sets the AVSession playback state.|
22| setLaunchAbility(ability: WantAgent, callback: AsyncCallback&lt;void&gt;): void | Starts a UIAbility.|
23| getController(callback: AsyncCallback&lt;AVSessionController&gt;): void | Obtains the controller of the AVSession.|
24| activate(callback: AsyncCallback&lt;void&gt;): void | Activates the AVSession.|
25| destroy(callback: AsyncCallback&lt;void&gt;): void | Destroys the AVSession.|
26
27## How to Develop
28
29To enable an audio and video application to access the AVSession service as a provider, proceed as follows:
30
311. Call an API in the **AVSessionManager** class to create and activate an **AVSession** object.
32
33   ```ts
34   import AVSessionManager from '@ohos.multimedia.avsession'; // Import the AVSessionManager module.
35
36   // Create an AVSession object.
37   async createSession() {
38       let session: AVSessionManager.AVSession = await AVSessionManager.createAVSession(this.context, 'SESSION_NAME', 'audio');
39       session.activate();
40       console.info(`session create done : sessionId : ${session.sessionId}`);
41   }
42   ```
43
442. Set AVSession information, which includes:
45   - AVMetadata
46   - AVPlaybackState
47
48   The controller will call an API in the **AVSessionController** class to obtain the information and display or process the information.
49
50   ```ts
51   async setSessionInfo() {
52     // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above.
53     let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
54     // The player logic that triggers changes in the session metadata and playback state is omitted here.
55     // Set necessary session metadata.
56     let metadata: AVSessionManager.AVMetadata = {
57       assetId: "0",
58       title: "TITLE",
59       artist: "ARTIST"
60     };
61     session.setAVMetadata(metadata).then(() => {
62       console.info('SetAVMetadata successfully');
63     }).catch((err) => {
64       console.info(`SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
65     });
66     // Set the playback state to paused and set isFavorite to false.
67     let playbackState: AVSessionManager.AVPlaybackState = {
68       state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PAUSE,
69       isFavorite:false
70     };
71     session.setAVPlaybackState(playbackState, function (err) {
72       if (err) {
73         console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
74       } else {
75         console.info('SetAVPlaybackState successfully');
76       }
77     });
78   }
79   ```
80
813. Set the UIAbility to be started by the controller. The UIAbility configured here is started when a user operates the UI of the controller, for example, clicking a widget in Media Controller.
82   The UIAbility is set through the **WantAgent** API. For details, see [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md).
83
84   ```ts
85   import WantAgent from "@ohos.app.ability.wantAgent";
86   ```
87
88   ```ts
89   // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above.
90   let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
91   let wantAgentInfo = {
92       wants: [
93           {
94               bundleName: "com.example.musicdemo",
95               abilityName: "com.example.musicdemo.MainAbility"
96           }
97       ],
98       operationType: WantAgent.OperationType.START_ABILITIES,
99       requestCode: 0,
100       wantAgentFlags: [WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
101   }
102   WantAgent.getWantAgent(wantAgentInfo).then((agent) => {
103       session.setLaunchAbility(agent)
104   })
105   ```
106
1074. Listen for control commands delivered by the controller, for example, Media Controller.
108   > **NOTE**
109   >
110   > After the provider registers a listener for the control command event, the event will be reflected in **getValidCommands()** of the controller. In other words, the controller determines that the command is valid and triggers the corresponding event as required. To ensure that the control commands delivered by the controller can be executed normally, the provider should not use a null implementation for listening.
111
112   ```ts
113   async setListenerForMesFromController() {
114     // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above.
115     let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
116     // Generally, logic processing on the player is implemented in the listener.
117     // After the processing is complete, use the setter to synchronize the playback information. For details, see the code snippet above.
118     session.on('play', () => {
119       console.info('on play , do play task');
120
121       // do some tasks ···
122     });
123     session.on('pause', () => {
124       console.info('on pause , do pause task');
125       // do some tasks ···
126     });
127     session.on('stop', () => {
128       console.info('on stop , do stop task');
129       // do some tasks ···
130     });
131     session.on('playNext', () => {
132       console.info('on playNext , do playNext task');
133       // do some tasks ···
134     });
135     session.on('playPrevious', () => {
136       console.info('on playPrevious , do playPrevious task');
137       // do some tasks ···
138     });
139   }
140   ```
141
1425. Obtain an **AVSessionController** object for this **AVSession** object for interaction.
143
144   ```ts
145   async createControllerFromSession() {
146     // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above.
147     let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
148
149     // Obtain an AVSessionController object for this AVSession object.
150     let controller: AVSessionManager.AVSessionController = await session.getController();
151
152     // The AVSessionController object can interact with the AVSession object, for example, by delivering a control command.
153     let avCommand: AVSessionManager.AVControlCommand = {command:'play'};
154     controller.sendControlCommand(avCommand);
155
156     // Alternatively, listen for state changes.
157     controller.on('playbackStateChange', 'all', (state: AVSessionManager.AVPlaybackState) => {
158
159       // do some things
160     });
161
162     // The AVSessionController object can perform many operations. For details, see the description of the controller.
163   }
164   ```
165
1666. When the audio and video application exits and does not need to continue playback, cancel the listener and destroy the **AVSession** object.
167   The code snippet below is used for canceling the listener for control commands:
168
169   ```ts
170   async unregisterSessionListener() {
171     // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above.
172     let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
173
174     // Cancel the listener of the AVSession object.
175     session.off('play');
176     session.off('pause');
177     session.off('stop');
178     session.off('playNext');
179     session.off('playPrevious');
180   }
181   ```
182
183     The code snippet below is used for destroying the AVSession object:
184
185   ```ts
186   async destroySession() {
187     // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above.
188     let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
189     // Destroy the AVSession object.
190     session.destroy(function (err) {
191       if (err) {
192         console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`);
193       } else {
194         console.info('Destroy : SUCCESS ');
195       }
196     });
197   }
198   ```
199