You can use the AVTranscoder to implement video transcoding. You can check whether the current device supports the AVTranscoder by calling canIUse. If the return value of canIUse("SystemCapability.Multimedia.Media.AVTranscoder") is true, the transcoding capability can be used.
This topic describes how to use the AVTranscoder to implement video transcoding, covering the process of starting, pausing, resuming, and exiting transcoding.
This sample consists of a UI (Index.ets) and a transcoding manager class (AVTranscoderManager.ets). The UI handles user interaction and progress display, and the transcoding manager class encapsulates the complete transcoding process. Import the following modules before development:
import { media } from '@kit.MediaKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
import { fileIo } from '@kit.CoreFileKit'; The overall structure of the transcoding manager class is as follows:
export class AVTranscoderDemo {
private avTranscoder: media.AVTranscoder | undefined = undefined;
private context: Context | undefined;
private currentProgress: number = 0;
constructor(context: Context | undefined) {
if (context != undefined) {
this.context = context;
}
}
// ...
} For details about the APIs, see AVTranscoder.
To forward, upload, or save the transcoded file, the application must call the system API await avTranscoder.release() after receiving the complete event. This ensures the integrity of the video file.
Create an AVTranscoder instance.
// 1. Create an AVTranscoder instance. this.avTranscoder = await media.createAVTranscoder();
Set the events to listen for.
| Event Type | Description |
|---|---|
| complete | Mandatory; used to listen for the completion of transcoding. |
| error | Mandatory; used to listen for errors that occur during transcoding. |
| progressUpdate | Used to listen for the transcoding progress. |
// Register avTranscoder callbacks.
setAVTranscoderCallback() {
if (canIUse('SystemCapability.Multimedia.Media.AVTranscoder')) {
if (this.avTranscoder != undefined) {
// Callback function for the completion of transcoding.
this.avTranscoder.on('complete', async () => {
console.info(`AVTranscoder is completed`);
await this.releaseTranscoderProcess();
});
// Callback function for errors.
this.avTranscoder.on('error', (err: BusinessError) => {
console.error(`AVTranscoder failed, code is ${err.code}, message is ${err.message}`);
});
// Callback function for progress updates.
this.avTranscoder.on('progressUpdate', (progress: number) => {
console.info(`AVTranscoder progressUpdate = ${progress}`);
this.currentProgress = progress;
})
}
}
}
// ...
// Obtain the current progress.
getCurrentProgress(): number {
console.info(`getCurrentProgress = ${this.currentProgress}`);
return this.currentProgress;
} Set the FD of the source video file (fdSrc).
The fdSrc in the following code example is for reference only. You need to verify resource availability and set it based on the actual situation:
If you use a local resource for transcoding, ensure that the resource file is available and use the app sandbox path to access the corresponding resource. For details, see Obtaining Application File Paths. For an introduction to the app sandbox and how to push files to it, see Application Sandbox.
Obtain the app file path through the Context property. You are advised to use getUIContext to obtain a UIContext instance and use getHostContext to call getContext of the bound instance. For details, see getHostContext.
To use ResourceManager.getRawFd() to open a HAP resource file descriptor, see getRawFd in ResourceManager.
import {AVTranscoderDemo} from '../transcoder/AVTranscoderManager'
@Entry
@Component
struct Index {
// Obtain the context of the ability to which the current component belongs and obtain the application file path through the context.
private context:Context | undefined = this.getUIContext().getHostContext();
// Obtain the AVTranscoder instance.
@State avTranscoder: AVTranscoderDemo = new AVTranscoderDemo(this.context);
build() {
RelativeContainer() {
Column() {
Button($r('app.string.StartTranscoder'))
.onClick(async () => {
console.info(`Button put`);
await this.avTranscoder.avTranscoderDemo();
})
.id('AVTranscoderButton')
Progress({ value: 0, total: 100, type: ProgressType.Linear }).value(this.avTranscoder.getCurrentProgress())
.height(50)
.width('80%')
}
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
}
.height('100%')
.width('100%')
}
} try {
// Obtain the file descriptor of the input file. H264_AAC.mp4 is a preset resource in the rawfile directory. Replace it with the actual one.
let fileDescriptor = await this.context.resourceManager.getRawFd('H264_AAC.mp4');
// Set fdSrc used for transcoding.
this.avTranscoder.fdSrc = fileDescriptor;
} catch (error) {
console.error('Failed to get the file descriptor, please check the resource and path.');
} Set the FD of the target video file (fdDst).
fdDst specifies the FD of the output file after transcoding. The value is a number. You must call @ohos.file.fs (File Management) to implement access to the application file. For details, see Accessing Application Files (ArkTS).
let outputFilePath = this.context.filesDir + '/output.mp4'; let file = fileIo.openSync(outputFilePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); // Set fdDst of the output file. this.avTranscoder.fdDst = file.fd;
Set audio and video transcoding parameters and call prepare().
private avConfig: media.AVTranscoderConfig = {
audioBitrate: 100000, // Audio bit rate.
audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format.
fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Container format.
videoBitrate: 200000, // Video bit rate.
videoCodec: media.CodecMimeType.VIDEO_AVC, // Video encoding format.
}; // 3. Set transcoding parameters to complete the preparations. await this.avTranscoder.prepare(this.avConfig);
Call start() to start transcoding.
// 4. Start transcoding. await this.avTranscoder.start();
Call pause() to pause transcoding.
// Process of pausing transcoding.
async pauseTranscoderProcess() {
if (canIUse('SystemCapability.Multimedia.Media.AVTranscoder')) {
if (this.avTranscoder != undefined) { // It is reasonable to call pause only after start is called and returns a value.
await this.avTranscoder.pause();
}
}
} Call resume() to resume transcoding.
// Resume the corresponding transcoding process.
async resumeTranscoderProcess() {
if (canIUse('SystemCapability.Multimedia.Media.AVTranscoder')) {
if (this.avTranscoder != undefined) { // It is reasonable to call resume only after pause is called and returns a value.
await this.avTranscoder.resume();
}
}
} Call release() to destroy the instance and exit transcoding.
// Release the transcoding process.
async releaseTranscoderProcess() {
if (canIUse('SystemCapability.Multimedia.Media.AVTranscoder')) {
if (this.avTranscoder != undefined) {
// 1. Release the AVTranscoder instance.
await this.avTranscoder.release();
let lastFdDst = this.avTranscoder.fdDst;
let lastFdSrc = this.avTranscoder.fdSrc;
this.avTranscoder = undefined;
// 2. Close the FD of the output file.
if (lastFdDst != undefined) {
fileIo.closeSync(lastFdDst);
}
// 3. Close the transcoding source file fd.
if (lastFdSrc != undefined) {
fileIo.closeSync(lastFdSrc.fd);
}
}
}
} A complete example of starting, pausing, resuming, and completing transcoding.
// A complete example of starting, pausing, resuming, and completing transcoding.
async avTranscoderDemo() {
await this.startTranscoderProcess(); // Start transcoding.
await this.pauseTranscoderProcess(); // Pause transcoding.
await this.resumeTranscoderProcess(); // Resume transcoding.
} Refer to the sample code below to implement transcoding, covering the process of starting, pausing, resuming, and exiting transcoding.
AVTranscoderArkTS
entry/src/main/ets/
└── pages
│ └── Index.ets (Transcoding UI)
│
└── transcoder
└── AVTranscoderManager.ets (Transcoding function)
entry/src/main/resources/
├── base
│ ├── element
│ │ ├── color.json
│ │ ├── float.json
│ │ └── string.json
│ └── media
│
└── rawfile
└── H264_AAC.mp4 (Video resource)