• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Interface (AVTranscoder)
2<!--Kit: Media Kit-->
3<!--Subsystem: Multimedia-->
4<!--Owner: @wang-haizhou6-->
5<!--Designer: @HmQQQ-->
6<!--Tester: @xchaosioda-->
7<!--Adviser: @zengyawen-->
8
9> **NOTE**
10>
11> - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
12> - The initial APIs of this interface are supported since API version 12.
13
14AVTranscoder is a transcoding management class. It provides APIs to transcode videos. Before calling any API in AVTranscoder, you must use [createAVTranscoder()](arkts-apis-media-f.md#mediacreateavtranscoder12) to create an AVTranscoder instance.
15
16For details about the AVTranscoder demo, see [Using AVTranscoder for Transcoding](../../media/media/using-avtranscoder-for-transcodering.md).
17
18## Modules to Import
19
20```ts
21import { media } from '@kit.MediaKit';
22```
23
24## Properties
25
26**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
27
28| Name   | Type                                | Read-Only| Optional| Description              |
29| ------- | ------------------------------------ | ---- | ---- | ------------------ |
30| fdSrc<sup>12+</sup>                                  | [AVFileDescriptor](arkts-apis-media-i.md#avfiledescriptor9)                       |  No | No  | Source media file descriptor, which specifies the data source.<br> **Example:**<br>There is a media file that stores continuous assets, the address offset is 0, and the byte length is 100. Its file descriptor is **AVFileDescriptor { fd = resourceHandle; offset = 0; length = 100; }**.<br>**NOTE**<br> - After the resource handle (FD) is transferred to an AVTranscoder instance, do not use the resource handle to perform other read and write operations, including but not limited to transferring this handle to other AVPlayer, AVMetadataExtractor, AVImageGenerator, or AVTranscoder instance. Competition occurs when multiple AVTranscoders use the same resource handle to read and write files at the same time, resulting in errors in obtaining data.|
31| fdDst<sup>12+</sup>                               | number                 |  No | No  | Destination media file descriptor, which specifies the data source. After creating an AVTranscoder instance, you must set both **fdSrc** and **fdDst**.<br>**NOTE**<br> - After the resource handle (FD) is transferred to an AVTranscoder instance, do not use the resource handle to perform other read and write operations, including but not limited to transferring this handle to other AVPlayer, AVMetadataExtractor, AVImageGenerator, or AVTranscoder instance. Competition occurs when multiple AVTranscoders use the same resource handle to read and write files at the same time, resulting in errors in obtaining data.|
32
33## prepare<sup>12+</sup>
34
35prepare(config: AVTranscoderConfig): Promise\<void>
36
37Sets video transcoding parameters. This API uses a promise to return the result.
38
39**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
40
41**Parameters**
42
43| Name| Type                                  | Mandatory| Description                      |
44| ------ | -------------------------------------- | ---- | -------------------------- |
45| config | [AVTranscoderConfig](arkts-apis-media-i.md#avtranscoderconfig12) | Yes  | Video transcoding parameters to set.<!--RP1--><!--RP1End-->|
46
47**Return value**
48
49| Type          | Description                                      |
50| -------------- | ------------------------------------------ |
51| Promise\<void> | Promise that returns no value.|
52
53**Error codes**
54
55For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Media Error Codes](errorcode-media.md).
56
57| ID| Error Message                              |
58| -------- | -------------------------------------- |
59| 401  | The parameter check failed. Return by promise. |
60| 5400102  | Operation not allowed. Return by promise. |
61| 5400103  | IO error. Return by promise.              |
62| 5400105  | Service died. Return by promise.       |
63| 5400106  | Unsupported format. Returned by promise.  |
64
65**Example**
66
67```ts
68import { BusinessError } from '@kit.BasicServicesKit';
69import { media } from '@kit.MediaKit';
70
71async function test() {
72  // Create an AVTranscoder instance.
73  let avTranscoder = await media.createAVTranscoder();
74  // Configure the parameters based on those supported by the hardware device.
75  let avTranscoderConfig: media.AVTranscoderConfig = {
76    audioBitrate : 200000,
77    audioCodec : media.CodecMimeType.AUDIO_AAC,
78    fileFormat : media.ContainerFormatType.CFT_MPEG_4,
79    videoBitrate : 3000000,
80    videoCodec : media.CodecMimeType.VIDEO_AVC,
81  };
82
83  avTranscoder.prepare(avTranscoderConfig).then(() => {
84    console.info('prepare success');
85  }).catch((err: BusinessError) => {
86    console.error('prepare failed and catch error is ' + err.message);
87  });
88}
89```
90
91## start<sup>12+</sup>
92
93start(): Promise\<void>
94
95Starts transcoding. This API uses a promise to return the result.
96
97This API can be called only after the [prepare()](#prepare12) API is called.
98
99**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
100
101**Return value**
102
103| Type          | Description                                 |
104| -------------- | ------------------------------------- |
105| Promise\<void> | Promise that returns no value.|
106
107**Error codes**
108
109For details about the error codes, see [Media Error Codes](errorcode-media.md).
110
111| ID| Error Message                              |
112| -------- | -------------------------------------- |
113| 5400102  | Operation not allowed. Return by promise. |
114| 5400103  | IO error. Return by promise.           |
115| 5400105  | Service died. Return by promise.       |
116
117**Example**
118
119```ts
120import { BusinessError } from '@kit.BasicServicesKit';
121import { media } from '@kit.MediaKit';
122
123async function test() {
124  // Create an AVTranscoder instance.
125  let avTranscoder = await media.createAVTranscoder();
126  avTranscoder.start().then(() => {
127    console.info('start AVTranscoder success');
128  }).catch((err: BusinessError) => {
129    console.error('start AVTranscoder failed and catch error is ' + err.message);
130  });
131}
132```
133
134## pause<sup>12+</sup>
135
136pause(): Promise\<void>
137
138Pauses transcoding. This API uses a promise to return the result.
139
140This API can be called only after the [start()](#start12) API is called. You can call [resume()](#resume12) to resume transcoding.
141
142**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
143
144**Return value**
145
146| Type          | Description                                 |
147| -------------- | ------------------------------------- |
148| Promise\<void> | Promise that returns no value.|
149
150**Error codes**
151
152For details about the error codes, see [Media Error Codes](errorcode-media.md).
153
154| ID| Error Message                              |
155| -------- | -------------------------------------- |
156| 5400102  | Operation not allowed. Return by promise. |
157| 5400103  | IO error. Return by promise.           |
158| 5400105  | Service died. Return by promise.       |
159
160**Example**
161
162```ts
163import { BusinessError } from '@kit.BasicServicesKit';
164import { media } from '@kit.MediaKit';
165
166async function test() {
167  // Create an AVTranscoder instance.
168  let avTranscoder = await media.createAVTranscoder();
169  avTranscoder.pause().then(() => {
170    console.info('pause AVTranscoder success');
171  }).catch((err: BusinessError) => {
172    console.error('pause AVTranscoder failed and catch error is ' + err.message);
173  });
174}
175```
176
177## resume<sup>12+</sup>
178
179resume(): Promise\<void>
180
181Resumes transcoding. This API uses a promise to return the result.
182
183This API can be called only after the [pause()](#pause12) API is called.
184
185**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
186
187**Return value**
188
189| Type          | Description                                 |
190| -------------- | ------------------------------------- |
191| Promise\<void> | Promise that returns no value.|
192
193**Error codes**
194
195For details about the error codes, see [Media Error Codes](errorcode-media.md).
196
197| ID| Error Message                              |
198| -------- | -------------------------------------- |
199| 5400102  | Operation not allowed. Return by promise. |
200| 5400103  | IO error. Return by promise.           |
201| 5400105  | Service died. Return by promise.       |
202
203**Example**
204
205```ts
206import { BusinessError } from '@kit.BasicServicesKit';
207import { media } from '@kit.MediaKit';
208
209async function test() {
210  // Create an AVTranscoder instance.
211  let avTranscoder = await media.createAVTranscoder();
212  avTranscoder.resume().then(() => {
213    console.info('resume AVTranscoder success');
214  }).catch((err: BusinessError) => {
215    console.error('resume AVTranscoder failed and catch error is ' + err.message);
216  });
217}
218```
219
220## cancel<sup>12+</sup>
221
222cancel(): Promise\<void>
223
224Cancels transcoding. This API uses a promise to return the result.
225
226This API can be called only after the [prepare()](#prepare12), [start()](#start12), [pause()](#pause12), or [resume()](#resume12) API is called.
227
228**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
229
230**Return value**
231
232| Type          | Description                                 |
233| -------------- | ------------------------------------- |
234| Promise\<void> | Promise that returns no value.|
235
236**Error codes**
237
238For details about the error codes, see [Media Error Codes](errorcode-media.md).
239
240| ID| Error Message                              |
241| -------- | -------------------------------------- |
242| 5400102  | Operation not allowed. Return by promise. |
243| 5400103  | IO error. Return by promise.           |
244| 5400105  | Service died. Return by promise.       |
245
246**Example**
247
248```ts
249import { BusinessError } from '@kit.BasicServicesKit';
250import { media } from '@kit.MediaKit';
251
252async function test() {
253  // Create an AVTranscoder instance.
254  let avTranscoder = await media.createAVTranscoder();
255  avTranscoder.cancel().then(() => {
256    console.info('cancel AVTranscoder success');
257  }).catch((err: BusinessError) => {
258    console.error('cancel AVTranscoder failed and catch error is ' + err.message);
259  });
260}
261```
262
263## release<sup>12+</sup>
264
265release(): Promise\<void>
266
267Releases the video transcoding resources. This API uses a promise to return the result.
268
269After the resources are released, you can no longer perform any operation on the AVTranscoder instance.
270
271**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
272
273**Return value**
274
275| Type          | Description                                       |
276| -------------- | ------------------------------------------- |
277| Promise\<void> | Promise that returns no value.|
278
279**Error codes**
280
281For details about the error codes, see [Media Error Codes](errorcode-media.md).
282
283| ID| Error Message                         |
284| -------- | --------------------------------- |
285| 5400102  | Operation not allowed. Return by promise. |
286| 5400105  | Service died. Return by promise. |
287
288**Example**
289
290```ts
291import { BusinessError } from '@kit.BasicServicesKit';
292import { media } from '@kit.MediaKit';
293
294async function test() {
295  // Create an AVTranscoder instance.
296  let avTranscoder = await media.createAVTranscoder();
297  avTranscoder.release().then(() => {
298    console.info('release AVTranscoder success');
299  }).catch((err: BusinessError) => {
300    console.error('release AVTranscoder failed and catch error is ' + err.message);
301  });
302}
303```
304
305## on('progressUpdate')<sup>12+</sup>
306
307on(type: 'progressUpdate', callback: Callback\<number>): void
308
309Subscribes to transcoding progress updates. An application can subscribe to only one transcoding progress update event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
310
311**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
312
313**Parameters**
314
315| Name  | Type    | Mandatory| Description                                                        |
316| -------- | -------- | ---- | ------------------------------------------------------------ |
317| type     | string   | Yes  | Event type, which is **'progressUpdate'** in this case. This event is triggered by the system during transcoding.|
318| callback | [Callback\<number>](../apis-basic-services-kit/js-apis-base.md#callback) | Yes  | Callback invoked when the event is triggered. **progress** is a number that indicates the current transcoding progress.|
319
320**Example**
321
322```ts
323import { media } from '@kit.MediaKit';
324
325async function test() {
326  // Create an AVTranscoder instance.
327  let avTranscoder = await media.createAVTranscoder();
328  avTranscoder.on('progressUpdate', (progress: number) => {
329    console.info('avTranscoder progressUpdate = ' + progress);
330  });
331}
332```
333
334## off('progressUpdate')<sup>12+</sup>
335
336off(type:'progressUpdate', callback?: Callback\<number>): void
337
338Unsubscribes from transcoding progress updates.
339
340**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
341
342**Parameters**
343
344| Name| Type  | Mandatory| Description                                                        |
345| ------ | ------ | ---- | ------------------------------------------------------------ |
346| type   | string | Yes  | Event type, which is **'progressUpdate'** in this case.|
347| callback | [Callback\<number>](../apis-basic-services-kit/js-apis-base.md#callback) | No  | Called that has been registered to listen for progress updates. You are advised to use the default value because only the last registered callback is retained in the current callback mechanism.|
348
349**Example**
350
351```ts
352import { media } from '@kit.MediaKit';
353
354async function test() {
355  // Create an AVTranscoder instance.
356  let avTranscoder = await media.createAVTranscoder();
357  avTranscoder.off('progressUpdate');
358}
359```
360
361## on('error')<sup>12+</sup>
362
363on(type: 'error', callback: ErrorCallback): void
364
365Subscribes to AVTranscoder errors. If this event is reported, call [release()](#release12) to exit the transcoding.
366
367An application can subscribe to only one AVTranscoder error event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
368
369**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
370
371**Parameters**
372
373| Name  | Type         | Mandatory| Description                                                        |
374| -------- | ------------- | ---- | ------------------------------------------------------------ |
375| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.|
376| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
377
378**Error codes**
379
380For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Media Error Codes](errorcode-media.md).
381
382| ID| Error Message                                  |
383| -------- | ------------------------------------------ |
384| 401      | The parameter check failed. |
385| 801      | Capability not supported. |
386| 5400101  | No memory.            |
387| 5400102  | Operation not allowed. |
388| 5400103  | I/O error.              |
389| 5400104  | Time out.            |
390| 5400105  | Service died.           |
391| 5400106  | Unsupported format.      |
392
393**Example**
394
395```ts
396import { BusinessError } from '@kit.BasicServicesKit';
397import { media } from '@kit.MediaKit';
398
399async function test() {
400  // Create an AVTranscoder instance.
401  let avTranscoder = await media.createAVTranscoder();
402  avTranscoder.on('error', (err: BusinessError) => {
403    console.info('case avTranscoder.on(error) called, errMessage is ' + err.message);
404  });
405}
406```
407
408## off('error')<sup>12+</sup>
409
410off(type:'error', callback?: ErrorCallback): void
411
412Unsubscribes from AVTranscoder errors. After the unsubscription, your application can no longer receive AVTranscoder errors.
413
414**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
415
416**Parameters**
417
418| Name| Type  | Mandatory| Description                                                        |
419| ------ | ------ | ---- | ------------------------------------------------------------ |
420| type   | string | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during transcoding.|
421| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | No  | Callback that has been registered to listen for AVTranscoder errors.|
422
423**Example**
424
425```ts
426import { media } from '@kit.MediaKit';
427
428async function test() {
429  // Create an AVTranscoder instance.
430  let avTranscoder = await media.createAVTranscoder();
431  avTranscoder.off('error');
432}
433```
434
435## on('complete')<sup>12+</sup>
436
437on(type: 'complete', callback: Callback\<void>): void
438
439Subscribes to the event indicating that transcoding is complete. An application can subscribe to only one transcoding completion event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
440
441When this event is reported, the current transcoding operation is complete. You need to call [release()](#release12) to exit the transcoding.
442
443**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
444
445**Parameters**
446
447| Name  | Type    | Mandatory| Description                                                        |
448| -------- | -------- | ---- | ------------------------------------------------------------ |
449| type     | string   | Yes  | Event type, which is **'complete'** in this case. This event is triggered by the system during transcoding.|
450| callback | [Callback\<void>](../apis-basic-services-kit/js-apis-base.md#callback) | Yes  | Callback that has been registered to listen for transcoding completion events.|
451
452**Example**
453
454```ts
455import { media } from '@kit.MediaKit';
456
457async function test() {
458  let avTranscoder: media.AVTranscoder | undefined = undefined;
459  // Create an AVTranscoder instance.
460  avTranscoder = await media.createAVTranscoder();
461  avTranscoder.on('complete', async () => {
462    console.info('avTranscoder complete');
463    if (avTranscoder != undefined) {
464      // Listen for transcoding completion events.
465      // Ensure that avTranscoder.release() has released the AVTranscoder instance before you proceed with forwarding, uploading, or storing the transcoded file.
466      await avTranscoder.release();
467      avTranscoder = undefined;
468    }
469  });
470}
471```
472
473## off('complete')<sup>12+</sup>
474
475off(type:'complete', callback?: Callback\<void>): void
476
477Unsubscribes from the event indicating that transcoding is complete.
478
479**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
480
481**Parameters**
482
483| Name| Type  | Mandatory| Description                                                        |
484| ------ | ------ | ---- | ------------------------------------------------------------ |
485| type   | string | Yes  | Event type, which is **'complete'** in this case.|
486| callback | [Callback\<void>](../apis-basic-services-kit/js-apis-base.md#callback) | No  | Callback that has been registered to listen for transcoding completion events.|
487
488**Example**
489
490```ts
491import { media } from '@kit.MediaKit';
492
493async function test() {
494  // Create an AVTranscoder instance.
495  let avTranscoder = await media.createAVTranscoder();
496  avTranscoder.off('complete');
497}
498```
499