• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Using AVTranscoder to Transcode Videos (ArkTS)
2
3You can use the [AVTranscoder](media-kit-intro.md#avtranscoder) to implement video transcoding<!--RP1--><!--RP1End-->. You can check whether the current device supports the AVTranscoder by calling [canIUse](../../reference/common/js-apis-syscap.md). If the return value of canIUse("SystemCapability.Multimedia.Media.AVTranscoder") is **true**, the transcoding capability can be used.
4
5This topic describes how to use the AVTranscoder to implement video transcoding, covering the process of starting, pausing, resuming, and exiting transcoding.
6
7## How to Develop
8
9Read [AVTranscoder](../../reference/apis-media-kit/js-apis-media.md#avtranscoder12) for the API reference.
10
111. Create an **avTranscoder** instance.
12
13   ```ts
14   import { media } from '@kit.MediaKit';
15   import { BusinessError } from '@kit.BasicServicesKit';
16
17   let avTranscoder: media.AVTranscoder;
18   media.createAVTranscoder().then((transcoder: media.AVTranscoder) => {
19     avTranscoder = transcoder;
20     // Perform other operations after avTranscoder is assigned a value.
21   }, (error: BusinessError) => {
22     console.error(`createAVTranscoder failed`);
23   });
24   ```
25
262. Set the events to listen for.
27
28   | Event Type| Description|
29   | -------- | -------- |
30   | complete | Mandatory; used to listen for the completion of transcoding.|
31   | error | Mandatory; used to listen for AVTranscoder errors.|
32
33   ```ts
34   import { BusinessError } from '@kit.BasicServicesKit';
35
36   // Callback function for the completion of transcoding.
37   avTranscoder.on('complete', () => {
38     console.log(`transcoder is completed`);
39     // Listen for transcoding completion events.
40   });
41
42   // Callback function for errors.
43   avTranscoder.on('error', (err: BusinessError) => {
44     console.error(`avTranscoder failed, code is ${err.code}, message is ${err.message}`);
45   });
46   ```
47
483. Set the FD of the source video file.
49   > **NOTE**
50   >
51   > The **fdSrc** value in the code snippet below is for reference only. You need to check the media asset validity and set **fdSrc** based on service requirements.
52   >
53   > - If local files are used for transcoding, ensure that the files are available and the application sandbox path is used for access. For details about how to obtain the application sandbox path, see [Obtaining Application File Paths](../../application-models/application-context-stage.md#obtaining-application-file-paths). For details about the application sandbox and how to push files to the application sandbox directory, see [File Management](../../file-management/app-sandbox-directory.md).
54   >
55   > - You can also use **ResourceManager.getRawFd()** to obtain the FD of a file packed in the HAP file. For details, see [ResourceManager API Reference](../../reference/apis-localization-kit/js-apis-resource-manager.md#getrawfd9).
56
57   ```ts
58   import resourceManager from '@ohos.resourceManager';
59   import { common } from '@kit.AbilityKit';
60
61   let context = getContext(this) as common.UIAbilityContext;
62   let fileDescriptor = await context.resourceManager.getRawFd('H264_AAC.mp4');
63   // Set fdSrc used for transcoding.
64   this.avTranscoder.fdSrc = fileDescriptor;
65   ```
66
674. Set the FD of the target video file.
68   > **NOTE**
69   >
70   > **fdDst** specifies the FD of the output file after transcoding. The value is a number. You must call [ohos.file.fs of Core File Kit](../../reference/apis-core-file-kit/js-apis-file-fs.md) to implement access to the application file. For details, see [Application File Access and Management](../../file-management/app-file-access.md).
71
72   ```ts
73   // Set fdDst of the output file.
74   this.avTranscoder.fdDst = 55; // Obtain the file descriptor of the created video file by referring to the sample code in Application File Access and Management.
75   ```
76
775. Set video transcoding parameters and call **prepare()**.
78
79   > **NOTE**
80   >
81   > Only transcoding-related parameters are set in the input parameter **avConfig** of the **prepare()** API.
82
83   ```ts
84   import { media } from '@kit.MediaKit';
85   import { BusinessError } from '@kit.BasicServicesKit';
86
87   let avConfig: media.AVTranscoderConfig = {
88     audioBitrate: 100000, // Audio bit rate.
89     audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format.
90     fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Container format.
91     videoBitrate: 2000000, // Video bit rate.
92     videoCodec: media.CodecMimeType.VIDEO_AVC, // Video encoding format.
93     videoFrameWidth: 640, // Video frame width: 640.
94     videoFrameHeight: 480, // Video frame height: 480.
95   };
96   avTranscoder.prepare(avConfig).then(() => {
97     console.log('Invoke prepare succeeded.');
98   }, (err: BusinessError) => {
99     console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`);
100   });
101   ```
102
1036. Call **start()** to start transcoding.
104
105   ```ts
106   // Start transcoding.
107   avTranscoder.start();
108   ```
109
1107. Call **pause()** to pause transcoding.
111
112   ```ts
113   // Pause transcoding.
114   avTranscoder.pause();
115   ```
116
1178. Call **resume()** to resume transcoding.
118
119   ```ts
120   // Resume transcoding.
121   avTranscoder.resume();
122   ```
123
1248. Call **cancel()** to cancel transcoding.
125
126   ```ts
127   // Cancel transcoding.
128   avTranscoder.cancel();
129   ```
130
1319. Call **release()** to destroy the instance and exit transcoding.
132
133   ```ts
134   // Destroy the instance.
135   avTranscoder.release();
136   ```
137
138## Sample Code
139
140  Refer to the sample code below to implement transcoding, covering the process of starting, pausing, resuming, and exiting transcoding.
141
142```ts
143import { media } from '@kit.MediaKit';
144import { BusinessError } from '@kit.BasicServicesKit';
145import { common } from '@kit.AbilityKit';
146
147export class AVTranscoderDemo {
148  private avTranscoder: media.AVTranscoder | undefined = undefined;
149  private avConfig: media.AVTranscoderConfig = {
150    audioBitrate: 100000, // Audio bit rate.
151    audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format.
152    fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Container format.
153    videoBitrate: 200000, // Video bit rate.
154    videoCodec: media.CodecMimeType.VIDEO_AVC, // Video encoding format.
155    videoFrameWidth: 640, // Video frame width.
156    videoFrameHeight: 480, // Video frame height.
157  };
158
159  // Set AVTranscoder callback functions.
160  setAVTranscoderCallback() {
161    if (canIUse("SystemCapability.Multimedia.Media.AVTranscoder")) {
162      if (this.avTranscoder != undefined) {
163        // Callback function for the completion of transcoding.
164        this.avTranscoder.on('complete', async () => {
165          console.log(`AVTranscoder is completed`);
166          await this.releaseTranscoderingProcess();
167        });
168        // Callback function for errors.
169        this.avTranscoder.on('error', (err: BusinessError) => {
170          console.error(`AVTranscoder failed, code is ${err.code}, message is ${err.message}`);
171        });
172      }
173    }
174  }
175
176  // Process of starting transcoding.
177  async startTranscoderingProcess() {
178    if (canIUse("SystemCapability.Multimedia.Media.AVTranscoder")) {
179      if (this.avTranscoder != undefined) {
180        await this.avTranscoder.release();
181        this.avTranscoder = undefined;
182      }
183      // 1. Create an avTranscoder instance.
184      this.avTranscoder = await media.createAVTranscoder();
185      this.setAVTranscoderCallback();
186      // 2. Obtain the source file FD and output file FD and assign them to avTranscoder. For details, see the FilePicker document.
187      let context = getContext(this) as common.UIAbilityContext;
188      let fileDescriptor = await context.resourceManager.getRawFd('H264_AAC.mp4');
189      this.avTranscoder.fdSrc = fileDescriptor;
190      this.avTranscoder.fdDst = 55;
191      // 3. Set transcoding parameters to complete the preparations.
192      await this.avTranscoder.prepare(this.avConfig);
193      // 4. Start transcoding.
194      await this.avTranscoder.start();
195    }
196  }
197
198  // Process of pausing transcoding.
199  async pauseTranscoderingProcess() {
200    if (canIUse("SystemCapability.Multimedia.Media.AVTranscoder")) {
201      if (this.avTranscoder != undefined) { // It is reasonable to call pause only after start is called and returns a value.
202        await this.avTranscoder.pause();
203      }
204    }
205  }
206
207  // Resume the transcoding process.
208  async resumeTranscoderingProcess() {
209    if (canIUse("SystemCapability.Multimedia.Media.AVTranscoder")) {
210      if (this.avTranscoder != undefined) { // It is reasonable to call resume only after pause is called and returns a value.
211        await this.avTranscoder.resume();
212      }
213    }
214  }
215
216  // Release the transcoding process.
217  async releaseTranscoderingProcess() {
218    if (canIUse("SystemCapability.Multimedia.Media.AVTranscoder")) {
219      if (this.avTranscoder != undefined) {
220        // 1. Release the avTranscoder instance.
221        await this.avTranscoder.release();
222        this.avTranscoder = undefined;
223        // 2. Close the FD of the output file.
224      }
225    }
226  }
227
228  // A complete example of starting, pausing, resuming, and exiting transcoding.
229  async avTranscoderDemo() {
230    await this.startTranscoderingProcess(); // Start transcoding.
231    await this.pauseTranscoderingProcess(); // Pause transcoding.
232    await this.resumeTranscoderingProcess(); // Resume transcoding.
233    await this.releaseTranscoderingProcess(); // Exit transcoding.
234  }
235}
236```
237