harmony 鸿蒙@ohos.multimedia.media (Media) (System API)

  • 2025-06-12
  • 浏览 (3)

@ohos.multimedia.media (Media) (System API)

The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources.

NOTE

  • 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.
  • This topic describes only system APIs provided by the module. For details about its public APIs, see @ohos.multimedia.media (Media).

Modules to Import

import { media } from '@kit.MediaKit';

media.createVideoRecorder9+

createVideoRecorder(callback: AsyncCallback<VideoRecorder>): void

Creates a VideoRecorder instance. This API uses an asynchronous callback to return the result.

Only one VideoRecorder instance can be created per device.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
callback AsyncCallback<VideoRecorder> Yes Callback used to return the result. If the operation is successful, a VideoRecorder instance is returned; otherwise, null is returned. The instance can be used to record video.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
202 Not system App.
5400101 No memory. Return by callback.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let videoRecorder: media.VideoRecorder;
media.createVideoRecorder((error: BusinessError, video: media.VideoRecorder) => {
  if (video != null) {
    videoRecorder = video;
    console.info('video createVideoRecorder success');
  } else {
    console.error(`video createVideoRecorder fail, error message:${error.message}`);
  }
});

media.createVideoRecorder9+

createVideoRecorder(): Promise<VideoRecorder>

Creates a VideoRecorder instance. This API uses a promise to return the result.

Only one VideoRecorder instance can be created per device.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

Type Description
Promise<VideoRecorder> Promise used to return the result. If the operation is successful, a VideoRecorder instance is returned; otherwise, null is returned. The instance can be used to record video.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400101 No memory. Return by promise.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let videoRecorder: media.VideoRecorder;
media.createVideoRecorder().then((video: media.VideoRecorder) => {
  if (video != null) {
    videoRecorder = video;
    console.info('video createVideoRecorder success');
  } else {
    console.error('video createVideoRecorder fail');
  }
}).catch((error: BusinessError) => {
  console.error(`video catchCallback, error message:${error.message}`);
});

media.reportAVScreenCaptureUserChoice12+

reportAVScreenCaptureUserChoice(sessionId: number, choice: string): Promise<void>

Reports the user selection result in the screen capture privacy dialog box to the AVScreenCapture server to determine whether to start screen capture. Screen capture starts only when the user touches a button to continue the operation.

This API is called by the system application that creates the dialog box.

System capability: SystemCapability.Multimedia.Media.AVScreenCapture

System API: This is a system API.

Parameters

Name Type Mandatory Description
sessionId number Yes Session ID of the AVScreenCapture service, which is sent to the application when the AVScreenCapture server starts the privacy dialog box.
choice string Yes User choice, including whether screen capture is agreed, selected display ID, and window ID. For details, see JsonData in the example below.

Error codes

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.
5400101 No memory. Return by promise.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { media } from '@kit.MediaKit';

class JsonData {
  public choice: string = 'true';
  public displayId: number|null = -1;
  public missionId: number|null = -1;
}
let sessionId: number = 0; // Use the ID of the session that starts the process.

try {
  const jsonData: JsonData = {
    choice: 'true',  // Replace it with the user choice.
    displayId: -1, // Replace it with the ID of the display selected by the user.
    missionId: -1,   // Replace it with the ID of the window selected by the user.
  }
  await media.reportAVScreenCaptureUserChoice(sessionId, JSON.stringify(jsonData));
} catch (error: BusinessError) {
  console.error(`reportAVScreenCaptureUserChoice error, error message: ${error.message}`);
}

media.getScreenCaptureMonitor18+

getScreenCaptureMonitor(): Promise<ScreenCaptureMonitor>

Obtains a ScreenCaptureMonitor instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Media.AVScreenCapture

System API: This is a system API.

Return value

Type Description
Promise<ScreenCaptureMonitor> Promise used to return the result. The instance can be used to query and monitor the status of the system screen recorder.
If the operation is successful, a ScreenCaptureMonitor instance is returned; otherwise, null is returned.

Error codes

For details about the error codes, see Universal Error Codes and Media Error Codes.

ID Error Message
202 Not System App.
5400101 No memory. Return by promise.

Example

let screenCaptureMonitor: media.ScreenCaptureMonitor;
try {
  screenCaptureMonitor = await media.getScreenCaptureMonitor();
} catch (err) {
  console.error(`getScreenCaptureMonitor failed, error message:${err.message}`);
}

media.createParallelSoundPool20+

createParallelSoundPool(maxStreams: number, audioRenderInfo: audio.AudioRendererInfo): Promise<SoundPool>

Creates a SoundPool instance. This API uses a promise to return the result.

If a SoundPool instance created using createSoundPool is used to play the same sound again, it stops the current audio and restarts the audio. However, if the instance is created using createParallelSoundPool, it keeps playing the first audio and starts the new one alongside it.

System capability: SystemCapability.Multimedia.Media.SoundPool

Parameters

Name Type Mandatory Description
maxStreams number Yes Maximum number of streams that can be played by the SoundPool instance. The value is an integer ranging from 1 to 32.
audioRenderInfo audio.AudioRendererInfo Yes Audio renderer parameters.

Return value

Type Description
Promise<SoundPool> Promise used to return the result. If the operation is successful, a SoundPool instance is returned; otherwise, null is returned. The instance is used for loading and playback.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400101 No memory. Return by promise.
202 System API error. Return by promise.

Example

import { audio } from '@kit.AudioKit';
import { BusinessError } from '@kit.BasicServicesKit';

let soundPool: media.SoundPool;
let audioRendererInfo: audio.AudioRendererInfo = {
  usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
  rendererFlags : 0
}

media.createParallelSoundPool(5, audioRendererInfo).then((soundpool_: media.SoundPool) => {
  if (soundpool_ != null) {
    soundPool = soundpool_;
    console.info('Succceeded in creating SoundPool');
  } else {
    console.error('Failed to create SoundPool');
  }
}, (error: BusinessError) => {
  console.error(`soundpool catchCallback, error message:${error.message}`);
});

PixelMapParams11+

Defines the format parameters of the video thumbnail to be obtained.

System capability: SystemCapability.Multimedia.Media.AVImageGenerator

Name Type Readable Writable Description
colorFormat PixelFormat Yes Yes Color format of the thumbnail.
System API: This is a system API.

PixelFormat11+

Enumerates the color formats supported by the video thumbnail.

System capability: SystemCapability.Multimedia.Media.AVImageGenerator

System API: This is a system API.

Name Value Description
RGB_565 2 RGB_565.
RGBA_8888 3 RGBA_8888.
RGB_888 5 RGB_888.

AVMetadataExtractor11+

Provides APIs to obtain metadata from media assets. Before calling any API of AVMetadataExtractor, you must use createAVMetadataExtractor() to create an AVMetadataExtractor instance.

getTimeByFrameIndex12+

getTimeByFrameIndex(index: number): Promise<number>

Obtains the video timestamp corresponding to a video frame number. Only MP4 video files are supported.

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

System API: This is a system API.

Parameters

Name Type Mandatory Description
index number Yes Video frame number.

Return value

Type Description
Promise<number> Promise used to return the timestamp, in microseconds.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
401 The parameter check failed. Return by promise.
5400102 Operation not allowed. Returned by promise.
5400106 Unsupported format. Returned by promise.

Example

import { media } from '@kit.MediaKit';
import { BusinessError } from '@kit.BasicServicesKit';

avMetadataExtractor.getTimeByFrameIndex(0).then((timeUs: number) => {
  console.info(`Succeeded getTimeByFrameIndex timeUs: ${timeUs}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to getTimeByFrameIndex ${err.message}`);
})

getFrameIndexByTime12+

getFrameIndexByTime(timeUs: number): Promise<number>

Obtains the video frame number corresponding to a video timestamp. Only MP4 video files are supported.

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

System API: This is a system API.

Parameters

Name Type Mandatory Description
timeUs number Yes Video timestamp, in microseconds.

Return value

Type Description
Promise<number> Promise used to return the video frame number.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
401 The parameter check failed. Return by promise.
5400102 Operation not allowed. Returned by promise.
5400106 Unsupported format. Returned by promise.

Example

import { media } from '@kit.MediaKit';
import { BusinessError } from '@kit.BasicServicesKit';

avMetadataExtractor.getFrameIndexByTime(0).then((index: number) => {
  console.info(`Succeeded getFrameIndexByTime index: ${index}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to getFrameIndexByTime ${err.message}`);
})

AVRecorder9+

A recording management class that provides APIs to record media assets. Before calling any API in AVRecorder, you must use createAVRecorder() to create an AVRecorder instance.

NOTE

To use the camera to record videos, the camera module is required. For details about how to use the APIs provided by the camera module, see Camera Management.

isWatermarkSupported13+

isWatermarkSupported(): Promise<boolean>

Checks whether the device supports the hardware digital watermark. This API uses a promise to return the result.

This API can be called after the prepare(), start(), or paused() event is triggered.

System capability: SystemCapability.Multimedia.Media.AVRecorder

System API: This is a system API.

Return value

Type Description
Promise<boolean> Promise used to return the check result. The value true means that the device supports the hardware digital watermark, and false means the opposite.

Example

import { BusinessError } from '@kit.BasicServicesKit';

avRecorder.isWatermarkSupported().then((isWatermarkSupported: boolean) => {
  console.info(`Succeeded in get, isWatermarkSupported: ${isWatermarkSupported}`);
}).catch((error: BusinessError) => {
  console.error(`Failed to get and catch error is ${error.message}`);
});

setWatermark13+

setWatermark(watermark: image.PixelMap, config: WatermarkConfig): Promise<void>

Sets a watermark for the AVRecorder. This API uses a promise to return the result.

This API can be called only after the prepare() event is triggered and before the start() event is triggered.

System capability: SystemCapability.Multimedia.Media.AVRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
watermark image.PixelMap Yes PixelMap data.
Currently, the following specifications are supported:
- Only RGBA8888 is supported.
- If the original image is 8K, the watermark resolution should be limited to a size of 3072 x 288; if the original image is 4K, the watermark resolution should be limited to a size of 1536 x 144.
config WatermarkConfig Yes Watermark configuration.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
401 The parameter check failed. Return by promise.
801 Capability not supported. Return by promise.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';

let watermark: image.PixelMap|undefined = undefined; // need data.
let watermarkConfig: media.WatermarkConfig = { top: 100, left: 100 }

avRecorder.setWatermark(watermark, watermarkConfig).then(() => {
  console.info('Succeeded in setWatermark');
}).catch((error: BusinessError) => {
  console.error(`Failed to setWatermark and catch error is ${error.message}`);
});

setMetadata18+

setMetadata(metadata: Record<string, string>): void

Sets custom metadata for the recording file of AVRecorder.

This API can be called only after the prepare() event is successfully triggered and before the stop() API is called.

System capability: SystemCapability.Multimedia.Media.AVRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
metadata [Record] Yes Tag and value of the metadata in key-value pairs.
- The first string is the tag.
- The second string is the value.

Return value

Type Description
void No result.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
202 Not System App.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let meta : Record<string, string> = {
   'com.openharmony.userdefine':'10',
   'com.openharmony.userdefine2':'20'
};

avRecorder.setMetadata(meta);

AVRecorderProfile9+

Describes the audio and video recording profile.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Name Type Mandatory Description
enableStableQualityMode18+ boolean No Whether to enable stable quality mode for video recording. This parameter is optional for video recording. The default value is false. If this parameter is set to true, the system will use a video encoding strategy designed to maintain stable quality.
System API: This is a system API.

VideoRecorder9+

NOTE This class is deprecated after AVRecorder9+ is released. You are advised to use AVRecorder instead.

Implements video recording. Before calling any API in the VideoRecorder class, you must use createVideoRecorder() to create a VideoRecorder instance.

Properties

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Name Type Readable Writable Description
state9+ VideoRecordState Yes No Video recording state.

prepare9+

prepare(config: VideoRecorderConfig, callback: AsyncCallback<void>): void

Sets video recording parameters. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.MICROPHONE

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
config VideoRecorderConfig Yes Video recording parameters to set.
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
201 Permission denied. Return by callback.
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.
5400102 Operation not allowed. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Configure the parameters based on those supported by the hardware device.
let videoProfile: media.VideoRecorderProfile = {
  audioBitrate : 48000,
  audioChannels : 2,
  audioCodec : media.CodecMimeType.AUDIO_AAC,
  audioSampleRate : 48000,
  fileFormat : media.ContainerFormatType.CFT_MPEG_4,
  videoBitrate : 2000000,
  videoCodec : media.CodecMimeType.VIDEO_AVC,
  videoFrameWidth : 640,
  videoFrameHeight : 480,
  videoFrameRate : 30
}

let videoConfig: media.VideoRecorderConfig = {
  audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
  videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
  profile : videoProfile,
  url : 'fd://xx', // The file must be created by the caller and granted with proper permissions.
  rotation : 0,
  location : { latitude : 30, longitude : 130 }
}

// asyncallback.
videoRecorder.prepare(videoConfig, (err: BusinessError) => {
  if (err == null) {
    console.info('prepare success');
  } else {
    console.error('prepare failed and error is ' + err.message);
  }
})

prepare9+

prepare(config: VideoRecorderConfig): Promise<void>

Sets video recording parameters. This API uses a promise to return the result.

Required permissions: ohos.permission.MICROPHONE

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
config VideoRecorderConfig Yes Video recording parameters to set.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
201 Permission denied. Return by promise.
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.
5400102 Operation not allowed. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Configure the parameters based on those supported by the hardware device.
let videoProfile: media.VideoRecorderProfile = {
  audioBitrate : 48000,
  audioChannels : 2,
  audioCodec : media.CodecMimeType.AUDIO_AAC,
  audioSampleRate : 48000,
  fileFormat : media.ContainerFormatType.CFT_MPEG_4,
  videoBitrate : 2000000,
  videoCodec : media.CodecMimeType.VIDEO_AVC,
  videoFrameWidth : 640,
  videoFrameHeight : 480,
  videoFrameRate : 30
}

let videoConfig: media.VideoRecorderConfig = {
  audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
  videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
  profile : videoProfile,
  url : 'fd://xx', // The file must be created by the caller and granted with proper permissions.
  rotation : 0,
  location : { latitude : 30, longitude : 130 }
}

// promise.
videoRecorder.prepare(videoConfig).then(() => {
  console.info('prepare success');
}).catch((err: BusinessError) => {
  console.error('prepare failed and catch error is ' + err.message);
});

getInputSurface9+

getInputSurface(callback: AsyncCallback<string>): void

Obtains the surface required for recording. This API uses an asynchronous callback to return the result. The caller obtains the surfaceBuffer from this surface and fills in the corresponding data.

Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp must be based on the system startup time.

This API can be called only after prepare() is called.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
callback AsyncCallback<string> Yes Callback used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400102 Operation not allowed. Return by callback.
5400103 I/O error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// asyncallback.
let surfaceID: string; // Surface ID passed to the external system.
videoRecorder.getInputSurface((err: BusinessError, surfaceId: string) => {
  if (err == null) {
    console.info('getInputSurface success');
    surfaceID = surfaceId;
  } else {
    console.error('getInputSurface failed and error is ' + err.message);
  }
});

getInputSurface9+

getInputSurface(): Promise<string>;

Obtains the surface required for recording. This API uses a promise to return the result. The caller obtains the surfaceBuffer from this surface and fills in the corresponding data.

Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp must be based on the system startup time.

This API can be called only after prepare() is called.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

Type Description
Promise<string> Promise used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400102 Operation not allowed. Return by promise.
5400103 I/O error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// promise.
let surfaceID: string; // Surface ID passed to the external system.
videoRecorder.getInputSurface().then((surfaceId: string) => {
  console.info('getInputSurface success');
  surfaceID = surfaceId;
}).catch((err: BusinessError) => {
  console.error('getInputSurface failed and catch error is ' + err.message);
});

start9+

start(callback: AsyncCallback<void>): void

Starts recording. This API uses an asynchronous callback to return the result.

This API can be called only after prepare() and getInputSurface() are called, because the data source must pass data to the surface first.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400102 Operation not allowed. Return by callback.
5400103 I/O error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// asyncallback.
videoRecorder.start((err: BusinessError) => {
  if (err == null) {
    console.info('start videorecorder success');
  } else {
    console.error('start videorecorder failed and error is ' + err.message);
  }
});

start9+

start(): Promise<void>

Starts recording. This API uses a promise to return the result.

This API can be called only after prepare() and getInputSurface() are called, because the data source must pass data to the surface first.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400102 Operation not allowed. Return by promise.
5400103 I/O error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// promise.
videoRecorder.start().then(() => {
  console.info('start videorecorder success');
}).catch((err: BusinessError) => {
  console.error('start videorecorder failed and catch error is ' + err.message);
});

pause9+

pause(callback: AsyncCallback<void>): void

Pauses recording. This API uses an asynchronous callback to return the result.

This API can be called only after start() is called. You can resume recording by calling resume().

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400102 Operation not allowed. Return by callback.
5400103 I/O error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// asyncallback.
videoRecorder.pause((err: BusinessError) => {
  if (err == null) {
    console.info('pause videorecorder success');
  } else {
    console.error('pause videorecorder failed and error is ' + err.message);
  }
});

pause9+

pause(): Promise<void>

Pauses recording. This API uses a promise to return the result.

This API can be called only after start() is called. You can resume recording by calling resume().

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400102 Operation not allowed. Return by promise.
5400103 I/O error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// promise.
videoRecorder.pause().then(() => {
  console.info('pause videorecorder success');
}).catch((err: BusinessError) => {
  console.error('pause videorecorder failed and catch error is ' + err.message);
});

resume9+

resume(callback: AsyncCallback<void>): void

Resumes recording. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400102 Operation not allowed. Return by callback.
5400103 I/O error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// asyncallback.
videoRecorder.resume((err: BusinessError) => {
  if (err == null) {
    console.info('resume videorecorder success');
  } else {
    console.error('resume videorecorder failed and error is ' + err.message);
  }
});

resume9+

resume(): Promise<void>

Resumes recording. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400102 Operation not allowed. Return by promise.
5400103 I/O error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// promise.
videoRecorder.resume().then(() => {
  console.info('resume videorecorder success');
}).catch((err: BusinessError) => {
  console.error('resume videorecorder failed and catch error is ' + err.message);
});

stop9+

stop(callback: AsyncCallback<void>): void

Stops recording. This API uses an asynchronous callback to return the result.

To start another recording, you must call prepare() and getInputSurface() again.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400102 Operation not allowed. Return by callback.
5400103 I/O error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// asyncallback.
videoRecorder.stop((err: BusinessError) => {
  if (err == null) {
    console.info('stop videorecorder success');
  } else {
    console.error('stop videorecorder failed and error is ' + err.message);
  }
});

stop9+

stop(): Promise<void>

Stops recording. This API uses a promise to return the result.

To start another recording, you must call prepare() and getInputSurface() again.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400102 Operation not allowed. Return by promise.
5400103 I/O error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// promise.
videoRecorder.stop().then(() => {
  console.info('stop videorecorder success');
}).catch((err: BusinessError) => {
  console.error('stop videorecorder failed and catch error is ' + err.message);
});

release9+

release(callback: AsyncCallback<void>): void

Releases the video recording resources. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// asyncallback.
videoRecorder.release((err: BusinessError) => {
  if (err == null) {
    console.info('release videorecorder success');
  } else {
    console.error('release videorecorder failed and error is ' + err.message);
  }
});

release9+

release(): Promise<void>

Releases the video recording resources. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// promise.
videoRecorder.release().then(() => {
  console.info('release videorecorder success');
}).catch((err: BusinessError) => {
  console.error('release videorecorder failed and catch error is ' + err.message);
});

reset9+

reset(callback: AsyncCallback<void>): void

Resets video recording. This API uses an asynchronous callback to return the result.

To start another recording, you must call prepare() and getInputSurface() again.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400103 I/O error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// asyncallback.
videoRecorder.reset((err: BusinessError) => {
  if (err == null) {
    console.info('reset videorecorder success');
  } else {
    console.error('reset videorecorder failed and error is ' + err.message);
  }
});

reset9+

reset(): Promise<void>

Resets video recording. This API uses a promise to return the result.

To start another recording, you must call prepare() and getInputSurface() again.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400103 I/O error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// promise.
videoRecorder.reset().then(() => {
  console.info('reset videorecorder success');
}).catch((err: BusinessError) => {
  console.error('reset videorecorder failed and catch error is ' + err.message);
});

on(‘error’)9+

on(type: ‘error’, callback: ErrorCallback): void

Subscribes to video recording error events. After an error event is reported, you must handle the event and exit the recording.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

Name Type Mandatory Description
type string Yes Event type, which is ‘error’ in this case.
This event is triggered when an error occurs during video recording.
callback ErrorCallback Yes Callback invoked when the event is triggered.

Error codes

For details about the error codes, see Media Error Codes.

ID Error Message
5400103 I/O error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// This event is reported when an error occurs during the retrieval of videoRecordState.
videoRecorder.on('error', (error: BusinessError) => { // Set the 'error' event callback.
  console.error(`audio error called, error: ${error}`);
})

VideoRecordState9+

Enumerates the video recording states. You can obtain the state through the state attribute.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Name Type Description
idle string The video recorder is idle.
prepared string The video recording parameters are set.
playing string Video recording is in progress.
paused string Video recording is paused.
stopped string Video recording is stopped.
error string Video recording is in the error state.

VideoRecorderConfig9+

Describes the video recording parameters.

The audioSourceType and videoSourceType parameters are used to distinguish video-only recording from audio and video recording. (For audio-only recording, use AVRecorder or AudioRecorder.) For video-only recording, set only videoSourceType. For audio and video recording, set both audioSourceType and videoSourceType.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Name Type Mandatory Description
audioSourceType AudioSourceType No Type of the audio source for video recording. This parameter is mandatory for audio recording.
videoSourceType VideoSourceType Yes Type of the video source for video recording.
profile VideoRecorderProfile Yes Video recording profile.
rotation number No Rotation angle of the recorded video. The value can only be 0 (default), 90, 180, or 270.
location Location No Geographical location of the recorded video. By default, the geographical location information is not recorded.
url string Yes Video output URL. Supported: fd://xx (fd number)

VideoRecorderProfile9+

Describes the video recording profile.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Name Type Mandatory Description
audioBitrate number No Audio encoding bit rate. This parameter is mandatory for audio recording.
audioChannels number No Number of audio channels. This parameter is mandatory for audio recording.
audioCodec CodecMimeType No Audio encoding format. This parameter is mandatory for audio recording.
audioSampleRate number No Audio sampling rate. This parameter is mandatory for audio recording.
fileFormat ContainerFormatType Yes Container format of a file.
videoBitrate number Yes Video encoding bit rate.
videoCodec CodecMimeType Yes Video encoding format.
videoFrameWidth number Yes Width of the recorded video frame.
videoFrameHeight number Yes Height of the recorded video frame.
videoFrameRate number Yes Video frame rate.

WatermarkConfig13+

Describes the watermark configuration set for the AVRecorder. The start point is the upper left corner of the image.

System capability: SystemCapability.Multimedia.Media.Core

System API: This is a system API.

Name Type Mandatory Description
top number Yes Pixel offset from the top edge of the image.
left number Yes Pixel offset from the left edge of the image.

ScreenCaptureMonitor18+

A class that provides APIs to query and monitor the system screen recorder status. Before calling any API, you must use getScreenCaptureMonitor() to obtain a ScreenCaptureMonitor instance.

Properties

System capability: SystemCapability.Multimedia.Media.AVScreenCapture

System API: This is a system API.

Name Type Readable Writable Description
isSystemScreenRecorderWorking18+ boolean Yes No Whether the system screen recorder is working.

on(‘systemScreenRecorder’)18+

on(type: ‘systemScreenRecorder’, callback: Callback<ScreenCaptureEvent>): void

Subscribes to state change events of the system screen recorder. From the ScreenCaptureEvent event reported, you can determine whether the system screen recorder is working.

System capability: SystemCapability.Multimedia.Media.AVScreenCapture

System API: This is a system API.

Parameters

Name Type Mandatory Description
type string Yes Event type, which is ‘systemScreenRecorder’ in this case.
This event is triggered when the state of the system screen recorder changes.
callback function Yes Callback invoked when the event is triggered, where ScreenCaptureEvent indicates the new state.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
202 Not System App.

Example


// This event is reported when the state of the system screen recorder changes.
screenCaptureMonitor.on('systemScreenRecorder', (event: media.ScreenCaptureEvent) => { 
  // Set the 'systemScreenRecorder' event callback.
  console.info(`system ScreenRecorder event: ${event}`);
})

off(‘systemScreenRecorder’)18+

off(type: ‘systemScreenRecorder’, callback?: Callback<ScreenCaptureEvent>): void

Unsubscribes from state change events of the system screen recorder.

System capability: SystemCapability.Multimedia.Media.AVScreenCapture

System API: This is a system API.

Parameters

Name Type Mandatory Description
type string Yes Event type, which is ‘systemScreenRecorder’ in this case.
This event is triggered when the state of the system screen recorder changes.
callback function No Callback invoked when the event is triggered, where ScreenCaptureEvent indicates the new state. If this parameter is not specified, the last subscription event is canceled.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
202 Not System App.

Example

screenCaptureMonitor.off('systemScreenRecorder');   

ScreenCaptureEvent18+

Enumerates the states available for the system screen recorder.

System capability: SystemCapability.Multimedia.Media.AVScreenCapture

System API: This is a system API.

Name Value Description
SCREENCAPTURE_STARTED 0 The system screen recorder starts screen capture.
SCREENCAPTURE_STOPPED 1 The system screen recorder stops screen capture.

enableDeviceLevelCapture20+

Specifies whether to capture the entire screen or half of the screen when the foldable PC is in the folded state.

System capability: SystemCapability.Multimedia.Media.AVScreenCapture

System API: This is a system API.

enableDeviceLevelCapture is an optional parameter in the AVScreenCaptureStrategy API. Its default value is false.

Name Type Mandatory Description
enableDeviceLevelCapture boolean No The value true means to capture the entire screen when the foldable PC is folded, and false means to capture half of the screen.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Media Kit

harmony 鸿蒙AVImageGenerator

harmony 鸿蒙AVMetadataExtractor

harmony 鸿蒙AVPlayer

harmony 鸿蒙AVPlayerCallback

harmony 鸿蒙AVRecorder

harmony 鸿蒙AVScreenCapture

harmony 鸿蒙OH_AVRecorder_Config

harmony 鸿蒙OH_AVRecorder_EncoderInfo

harmony 鸿蒙OH_AVRecorder_Location

0  赞