@ohos.multimedia.media (Media)

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.

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

This subsystem offers the following audio and video services:

Modules to Import

import media from '@ohos.multimedia.media';

media.createAVPlayer9+

createAVPlayer(callback: AsyncCallback<AVPlayer>): void

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

NOTE

  • A maximum of 13 instances can be created in video-only playback scenarios.
  • A maximum of 16 instances can be created in both audio and video playback scenarios.
  • The actual number of instances that can be created may be different. It depends on the specifications of the device chip in use. For example, in the case of RK3568, a maximum of 6 instances can be created in video-only playback scenarios.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
callback AsyncCallback<AVPlayer> Yes Callback used to return the result. If the operation is successful, an AVPlayer instance is returned; otherwise, null is returned. The instance can be used to play audio and video.

Error codes

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

ID Error Message
5400101 No memory. Return by callback.

Example

import { BusinessError } from '@ohos.base';

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

media.createAVPlayer9+

createAVPlayer(): Promise<AVPlayer>

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

NOTE

  • A maximum of 13 instances can be created in video-only playback scenarios.
  • A maximum of 16 instances can be created in both audio and video playback scenarios.
  • The actual number of instances that can be created may be different. It depends on the specifications of the device chip in use. For example, in the case of RK3568, a maximum of 6 instances can be created in video-only playback scenarios.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Return value

Type Description
Promise<AVPlayer> Promise used to return the result. If the operation is successful, an AVPlayer instance is returned; otherwise, null is returned. The instance can be used to play audio and 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 '@ohos.base';

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

media.createAVRecorder9+

createAVRecorder(callback: AsyncCallback<AVRecorder>): void

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

NOTE

  • A maximum of 2 instances can be created in audio and video recording scenarios.
  • Only one instance can perform audio recording on a device at one time, since all the applications share the audio channel. Any attempt to create the second instance for audio recording fails due to audio channel conflicts.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

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

Error codes

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

ID Error Message
5400101 No memory. Return by callback.

Example

import { BusinessError } from '@ohos.base';
let avRecorder: media.AVRecorder;

media.createAVRecorder((error: BusinessError, recorder: media.AVRecorder) => {
  if (recorder != null) {
    avRecorder = recorder;
    console.info('createAVRecorder success');
  } else {
    console.error(`createAVRecorder fail, error message:${error.message}`);
  }
});

media.createAVRecorder9+

createAVRecorder(): Promise<AVRecorder>

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

NOTE

  • A maximum of 2 instances can be created in audio and video recording scenarios.
  • Only one instance can perform audio recording on a device at one time, since all the applications share the audio channel. Any attempt to create the second instance for audio recording fails due to audio channel conflicts.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Return value

Type Description
Promise<AVRecorder> Promise used to return the result. If the operation is successful, an AVRecorder instance is returned; otherwise, null is returned. The instance can be used to record audio and 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 '@ohos.base';

let avRecorder: media.AVRecorder;
media.createAVRecorder().then((recorder: media.AVRecorder) => {
  if (recorder != null) {
    avRecorder = recorder;
    console.info('createAVRecorder success');
  } else {
    console.error('createAVRecorder fail');
  }
}).catch((error: BusinessError) => {
  console.error(`createAVRecorder catchCallback, error message:${error.message}`);
});

media.createAVMetadataExtractor11+

createAVMetadataExtractor(callback: AsyncCallback<AVMetadataExtractor>): void

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

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

Parameters

Name Type Mandatory Description
callback AsyncCallback<AVMetadataExtractor> Yes Callback used to return the result. If the operation is successful, an AVMetadataExtractor instance is returned; otherwise, null is returned. The interface can be used to obtain audio and video metadata.

Error codes

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

ID Error Message
5400101 No memory. Returned by callback.

Example

import { BusinessError } from '@ohos.base';

let avMetadataExtractor: media.AVMetadataExtractor;
media.createAVMetadataExtractor((error: BusinessError, extractor: media.AVMetadataExtractor) => {
  if (extractor != null) {
    avMetadataExtractor = extractor;
    console.info('createAVMetadataExtractor success');
  } else {
    console.error(`createAVMetadataExtractor fail, error message:${error.message}`);
  }
});

media.createAVMetadataExtractor11+

createAVMetadataExtractor(): Promise<AVMetadataExtractor>

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

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

Return value

Type Description
Promise<AVMetadataExtractor> Promise used to return the result. If the operation is successful, an AVMetadataExtractor instance is returned; otherwise, null is returned. The interface can be used to obtain audio and video metadata.

Error codes

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

ID Error Message
5400101 No memory. Returned by promise.

Example

import { BusinessError } from '@ohos.base';

let avMetadataExtractor: media.AVMetadataExtractor;
media.createAVMetadataExtractor().then((extractor: media.AVMetadataExtractor) => {
  if (extractor != null) {
    avMetadataExtractor = extractor;
    console.info('createAVMetadataExtractor success');
  } else {
    console.error('createAVMetadataExtractor fail');
  }
}).catch((error: BusinessError) => {
  console.error(`AVMetadataExtractor catchCallback, error message:${error.message}`);
});

media.createSoundPool10+

createSoundPool(maxStreams: number, audioRenderInfo: audio.AudioRendererInfo, callback: AsyncCallback<SoundPool>): void

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

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.
audioRenderInfo audio.AudioRendererInfo Yes Audio renderer parameters.
callback AsyncCallback<SoundPool> Yes Callback 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 callback.

Example

import audio from '@ohos.multimedia.audio'

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

media.createSoundPool(5, audioRendererInfo, (error, soundPool_: media.SoundPool) => {
  if (error) {
    console.error(`createSoundPool failed`)
    return;
  } else {
    soundPool = soundPool_;
    console.info(`createSoundPool success`)
  }
});

media.createSoundPool10+

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

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

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.
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.

Example

import audio from '@ohos.multimedia.audio'
import { BusinessError } from '@ohos.base';

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

media.createSoundPool(5, audioRendererInfo).then((soundpool_: media.SoundPool) => {
  if (soundpool_ != null) {
    soundPool = soundpool_;
    console.info('create SoundPool success');
  } else {
    console.error('create SoundPool fail');
  }
}, (error: BusinessError) => {
  console.error(`soundpool catchCallback, error message:${error.message}`);
});

AVErrorCode9+

Enumerates the media error codes.

System capability: SystemCapability.Multimedia.Media.Core

Name Value Description
AVERR_OK 0 The operation is successful.
AVERR_NO_PERMISSION 201 You do not have the permission to perform the operation.
AVERR_INVALID_PARAMETER 401 Invalid input parameter.
AVERR_UNSUPPORT_CAPABILITY 801 Unsupported API.
AVERR_NO_MEMORY 5400101 The system memory is insufficient or the number of services reaches the upper limit.
AVERR_OPERATE_NOT_PERMIT 5400102 The operation is not allowed in the current state or you do not have the permission to perform the operation.
AVERR_IO 5400103 The data stream is abnormal.
AVERR_TIMEOUT 5400104 The system or network response times out.
AVERR_SERVICE_DIED 5400105 The service process is dead.
AVERR_UNSUPPORT_FORMAT 5400106 The format of the media asset is not supported.
AVERR_AUDIO_INTERRUPTED11+ 5400107 The audio focus is interrupted.

MediaType8+

Enumerates the media types.

System capability: SystemCapability.Multimedia.Media.Core

Name Value Description
MEDIA_TYPE_AUD 0 Media.
MEDIA_TYPE_VID 1 Video.

CodecMimeType8+

Enumerates the codec MIME types.

System capability: SystemCapability.Multimedia.Media.Core

Name Value Description
VIDEO_H263 'video/h263' Video in H.263 format.
VIDEO_AVC 'video/avc' Video in AVC format.
VIDEO_MPEG2 'video/mpeg2' Video in MPEG-2 format.
VIDEO_MPEG4 'video/mp4v-es' Video in MPEG-4 format.
VIDEO_VP8 'video/x-vnd.on2.vp8' Video in VP8 format.
VIDEO_HEVC11+ 'video/hevc' Video in H.265 format.
AUDIO_AAC 'audio/mp4a-latm' Audio in MP4A-LATM format.
AUDIO_VORBIS 'audio/vorbis' Audio in Vorbis format.
AUDIO_FLAC 'audio/flac' Audio in FLAC format.

MediaDescriptionKey8+

Enumerates the media description keys.

System capability: SystemCapability.Multimedia.Media.Core

Name Value Description
MD_KEY_TRACK_INDEX 'track_index' Track index, which is a number.
MD_KEY_TRACK_TYPE 'track_type' Track type, which is a number. For details, see MediaType.
MD_KEY_CODEC_MIME 'codec_mime' Codec MIME type, which is a string.
MD_KEY_DURATION 'duration' Media duration, which is a number, in units of ms.
MD_KEY_BITRATE 'bitrate' Bit rate, which is a number, in units of bit/s.
MD_KEY_WIDTH 'width' Video width, which is a number, in units of pixel.
MD_KEY_HEIGHT 'height' Video height, which is a number, in units of pixel.
MD_KEY_FRAME_RATE 'frame_rate' Video frame rate, which is a number, in units of 100 fps.
MD_KEY_AUD_CHANNEL_COUNT 'channel_count' Number of audio channels, which is a number.
MD_KEY_AUD_SAMPLE_RATE 'sample_rate' Sampling rate, which is a number, in units of Hz.

BufferingInfoType8+

Enumerates the buffering event types.

System capability: SystemCapability.Multimedia.Media.Core

Name Value Description
BUFFERING_START 1 Buffering starts.
BUFFERING_END 2 Buffering ends.
BUFFERING_PERCENT 3 Buffering progress, in percent.
CACHED_DURATION 4 Cache duration, in ms.

StateChangeReason9+

Enumerates the reasons for the state transition of the AVPlayer or AVRecorder instance. The enum value is reported together with state.

System capability: SystemCapability.Multimedia.Media.Core

Name Value Description
USER 1 State transition triggered by user behavior. It happens when a user or the client calls an API.
BACKGROUND 2 State transition caused by background system behavior. For example, if an application does not have the permission of Media Controller, the application is forcibly suspended or stopped by the system when it switches to the background.

AVPlayer9+

A playback management class that provides APIs to manage and play media assets. Before calling any API in AVPlayer, you must use createAVPlayer() to create an AVPlayer instance.

For details about the audio and video playback demo, see Audio Playback and Video Playback.

Attributes

System capability: SystemCapability.Multimedia.Media.AVPlayer

Name Type Readable Writable Description
url9+ string Yes Yes URL of the media asset. It can be set only when the AVPlayer is in the idle state.
The video formats MP4, MPEG-TS, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, WAV, and FLAC are supported.
Example of supported URLs:
1. FD: fd://xx

2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
NOTE
WebM is no longer supported since API version 11.
fdSrc9+ AVFileDescriptor Yes Yes FD of the media asset. It can be set only when the AVPlayer is in the idle state.
This attribute is required when media assets of an application are continuously stored in a file.
The video formats MP4, MPEG-TS, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, WAV, and FLAC are supported.
Example:
Assume that a media file that stores continuous assets consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent media file, use src=fd://xx.
NOTE
WebM is no longer supported since API version 11.
dataSrc10+ AVDataSrcDescriptor Yes Yes Descriptor of a streaming media asset. It can be set only when the AVPlayer is in the idle state.
Use scenario: An application starts playing a media file while the file is still being downloaded from the remote to the local host.
The video formats MP4, MPEG-TS, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, WAV, and FLAC are supported.
Example:
A user is obtaining an audio and video file from a remote server and wants to play the downloaded file content. To implement this scenario, do as follows:
1. Obtain the total file size, in bytes. If the total size cannot be obtained, set fileSize to -1.
2. Implement the func callback to fill in data. If fileSize is -1, the format of func is func(buffer: ArrayBuffer, length: number), and the AVPlayer obtains data in sequence; otherwise, the format is func(buffer: ArrayBuffer, length: number, pos: number), and the AVPlayer seeks and obtains data in the required positions.
3. Set AVDataSrcDescriptor {fileSize = size, callback = func}.
Notes:
If the media file to play is in MP4/M4A format, ensure that the moov field (specifying the media information) is before the mdat field (specifying the media data) or the fields before the moov field is less than 10 MB. Otherwise, the parsing fails and the media file cannot be played.
NOTE
WebM is no longer supported since API version 11.
surfaceId9+ string Yes Yes Video window ID. By default, there is no video window. It can be set only when the AVPlayer is in the initialized state.
It is used to render the window for video playback and therefore is not required in audio-only playback scenarios.
Example:
Create a surface ID through XComponent.
loop9+ boolean Yes Yes Whether to loop playback. The value true means to loop playback, and false (default) means the opposite. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.
This setting is not supported in live mode.
videoScaleType9+ VideoScaleType Yes Yes Video scaling type. The default value is VIDEO_SCALE_TYPE_FIT. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.
audioInterruptMode9+ audio.InterruptMode Yes Yes Audio interruption mode. The default value is SHARE_MODE. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.
To take effect, this attribute must be set before play() is called for the first time.
audioRendererInfo10+ audio.AudioRendererInfo Yes Yes Audio renderer information. The default values of usage and rendererFlags are STREAM_USAGE_MUSIC and 0, respectively.
It can be set only when the AVPlayer is in the initialized state.
To take effect, this attribute must be set before prepare() is called for the first time.
audioEffectMode10+ audio.AudioEffectMode Yes Yes Audio effect mode. The audio effect mode is a dynamic attribute and is restored to the default value EFFECT_DEFAULT when usage of audioRendererInfo is changed. It can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.
state9+ AVPlayerState Yes No AVPlayer state. It can be used as a query parameter when the AVPlayer is in any state.
currentTime9+ number Yes No Current video playback position, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value -1 indicates an invalid value.
In live mode, -1 is returned by default.
duration9+ number Yes No Video duration, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value -1 indicates an invalid value.
In live mode, -1 is returned by default.
width9+ number Yes No Video width, in px. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value 0 indicates an invalid value.
height9+ number Yes No Video height, in px. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value 0 indicates an invalid value.

NOTE

After the resource handle (FD) is transferred to the AVPlayer, do not use the resource handle to perform read and write operations, including but not limited to transferring it to multiple AVPlayers. Competition occurs when multiple AVPlayers use the same resource handle to read and write files at the same time, resulting in playback errors.

on('stateChange')9+

on(type: 'stateChange', callback: (state: AVPlayerState, reason: StateChangeReason) => void): void

Subscribes to AVPlayer state changes.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'stateChange' in this case. This event can be triggered by both user operations and the system.
callback function Yes Callback invoked when the event is triggered. It reports the following information:
state: AVPlayerState, indicating the AVPlayer state.
reason: StateChangeReason, indicating the reason for the state transition.

Example

avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => {
  switch (state) {
    case 'idle':
      console.info('state idle called');
      break;
    case 'initialized':
      console.info('initialized prepared called');
      break;
    case 'prepared':
      console.info('state prepared called');
      break;
    case 'playing':
      console.info('state playing called');
      break;
    case 'paused':
      console.info('state paused called');
      break;
    case 'completed':
      console.info('state completed called');
      break;
    case 'stopped':
      console.info('state stopped called');
      break;
    case 'released':
      console.info('state released called');
      break;
    case 'error':
      console.info('state error called');
      break;
    default:
      console.info('unknown state :' + state);
      break;
  }
})

off('stateChange')9+

off(type: 'stateChange'): void

Unsubscribes from AVPlayer state changes.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'stateChange' in this case.

Example

avPlayer.off('stateChange')

on('error')9+

on(type: 'error', callback: ErrorCallback): void

Subscribes to AVPlayer errors. This event is used only for error prompt and does not require the user to stop playback control. If AVPlayerState is also switched to error, call reset() or release() to exit the playback.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'error' in this case. This event can be triggered by both user operations and the system.
callback ErrorCallback Yes Callback used to return the error code ID and error message.

Error codes

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

ID Error Message
201 Permission denied
401 The parameter check failed.
801 Capability not supported.
5400101 No Memory. Return by callback.
5400102 Operation not allowed.
5400103 I/O error
5400104 Time out
5400105 Service Died.
5400106 Unsupport Format.

Example

import { BusinessError } from '@ohos.base';

avPlayer.on('error', (error: BusinessError) => {
  console.info('error happened,and error message is :' + error.message)
  console.info('error happened,and error code is :' + error.code)
})

off('error')9+

off(type: 'error'): void

Unsubscribes from AVPlayer errors.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'error' in this case.

Example

avPlayer.off('error')

prepare9+

prepare(callback: AsyncCallback<void>): void

Prepares for audio and video playback. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the initialized state. The state changes can be detected by subscribing to the stateChange event.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
callback function 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.
5400106 Unsupport format. Return by callback.

Example

import { BusinessError } from '@ohos.base';

avPlayer.prepare((err: BusinessError) => {
  if (err == null) {
    console.info('prepare success');
  } else {
    console.error('prepare filed,error message is :' + err.message)
  }
})

prepare9+

prepare(): Promise<void>

Prepares for audio and video playback. This API uses a promise to return the result. It can be called only when the AVPlayer is in the initialized state. The state changes can be detected by subscribing to the stateChange event.

System capability: SystemCapability.Multimedia.Media.AVPlayer

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.
5400106 Unsupport format. Return by promise.

Example

import { BusinessError } from '@ohos.base';

avPlayer.prepare().then(() => {
  console.info('prepare success');
}, (err: BusinessError) => {
  console.error('prepare filed,error message is :' + err.message)
})

play9+

play(callback: AsyncCallback<void>): void

Starts to play an audio and video asset. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the prepared, paused, or completed state.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
callback function 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.

Example

import { BusinessError } from '@ohos.base';

avPlayer.play((err: BusinessError) => {
  if (err == null) {
    console.info('play success');
  } else {
    console.error('play filed,error message is :' + err.message)
  }
})

play9+

play(): Promise<void>

Starts to play an audio and video asset. This API uses a promise to return the result. It can be called only when the AVPlayer is in the prepared, paused, or completed state.

System capability: SystemCapability.Multimedia.Media.AVPlayer

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.

Example

import { BusinessError } from '@ohos.base';

avPlayer.play().then(() => {
  console.info('play success');
}, (err: BusinessError) => {
  console.error('play filed,error message is :' + err.message)
})

pause9+

pause(callback: AsyncCallback<void>): void

Pauses audio and video playback. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the playing state.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
callback function 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.

Example

import { BusinessError } from '@ohos.base';

avPlayer.pause((err: BusinessError) => {
  if (err == null) {
    console.info('pause success');
  } else {
    console.error('pause filed,error message is :' + err.message)
  }
})

pause9+

pause(): Promise<void>

Pauses audio and video playback. This API uses a promise to return the result. It can be called only when the AVPlayer is in the playing state.

System capability: SystemCapability.Multimedia.Media.AVPlayer

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.

Example

import { BusinessError } from '@ohos.base';

avPlayer.pause().then(() => {
  console.info('pause success');
}, (err: BusinessError) => {
  console.error('pause filed,error message is :' + err.message)
})

stop9+

stop(callback: AsyncCallback<void>): void

Stops audio and video playback. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the prepared, playing, paused, or completed state.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
callback function 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.

Example

import { BusinessError } from '@ohos.base';

avPlayer.stop((err: BusinessError) => {
  if (err == null) {
    console.info('stop success');
  } else {
    console.error('stop filed,error message is :' + err.message)
  }
})

stop9+

stop(): Promise<void>

Stops audio and video playback. This API uses a promise to return the result. It can be called only when the AVPlayer is in the prepared, playing, paused, or completed state.

System capability: SystemCapability.Multimedia.Media.AVPlayer

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.

Example

import { BusinessError } from '@ohos.base';

avPlayer.stop().then(() => {
  console.info('stop success');
}, (err: BusinessError) => {
  console.error('stop filed,error message is :' + err.message)
})

reset9+

reset(callback: AsyncCallback<void>): void

Resets audio and video playback. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the initialized, prepared, playing, paused, completed, stopped, or error state.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
callback function 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.

Example

import { BusinessError } from '@ohos.base';

avPlayer.reset((err: BusinessError) => {
  if (err == null) {
    console.info('reset success');
  } else {
    console.error('reset filed,error message is :' + err.message)
  }
})

reset9+

reset(): Promise<void>

Resets audio and video playback. This API uses a promise to return the result. It can be called only when the AVPlayer is in the initialized, prepared, playing, paused, completed, stopped, or error state.

System capability: SystemCapability.Multimedia.Media.AVPlayer

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.

Example

import { BusinessError } from '@ohos.base';

avPlayer.reset().then(() => {
  console.info('reset success');
}, (err: BusinessError) => {
  console.error('reset filed,error message is :' + err.message)
})

release9+

release(callback: AsyncCallback<void>): void

Releases the playback resources. This API uses an asynchronous callback to return the result. It can be called when the AVPlayer is in any state except released.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
callback function 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.

Example

import { BusinessError } from '@ohos.base';

avPlayer.release((err: BusinessError) => {
  if (err == null) {
    console.info('release success');
  } else {
    console.error('release filed,error message is :' + err.message)
  }
})

release9+

release(): Promise<void>

Releases the playback resources. This API uses a promise to return the result. It can be called when the AVPlayer is in any state except released.

System capability: SystemCapability.Multimedia.Media.AVPlayer

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.

Example

import { BusinessError } from '@ohos.base';

avPlayer.release().then(() => {
  console.info('release success');
}, (err: BusinessError) => {
  console.error('release filed,error message is :' + err.message)
})

getTrackDescription9+

getTrackDescription(callback: AsyncCallback<Array<MediaDescription>>): void

Obtains the audio and video track information. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the prepared, playing, or paused state. To obtain information about all audio and video tracks, this API must be called after the data loading callback is triggered.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
callback AsyncCallback<Array<MediaDescription>> Yes Callback used to return a MediaDescription array, which records the audio and video track information.

Error codes

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

ID Error Message
5400102 Operation not allowed. Return by callback.

Example

import { BusinessError } from '@ohos.base';

avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
  if ((arrList) != null) {
    console.info('getTrackDescription success');
  } else {
    console.error(`video getTrackDescription fail, error:${error}`);
  }
});

getTrackDescription9+

getTrackDescription(): Promise<Array<MediaDescription>>

Obtains the audio and video track information. This API uses a promise to return the result. It can be called only when the AVPlayer is in the prepared, playing, or paused state.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Return value

Type Description
Promise<Array<MediaDescription>> Promise used to return a MediaDescription array, which records the audio and video track information.

Error codes

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

ID Error Message
5400102 Operation not allowed. Return by promise.

Example

import { BusinessError } from '@ohos.base';

avPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => {
  console.info('getTrackDescription success');
}).catch((error: BusinessError) => {
  console.error(`video catchCallback, error:${error}`);
});

setDecryptionConfig11+

setDecryptionConfig(mediaKeySession: drm.MediaKeySession, secureVideoPath: boolean): void

Sets the decryption configuration. When receiving a mediaKeySystemInfoUpdate event, create the related configuration and set the decryption configuration based on the information in the reported event. Otherwise, the playback fails.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
mediaKeySession drm.MediaKeySession Yes Decryption session.
secureVideoPath boolean Yes Secure video channel. The value true means that a secure video channel is selected, and false means that a non-secure video channel is selected.

Example

For details about the DRM module, see js-apis-drm.md.

import drm from '@ohos.multimedia.drm'

// Create a media key system.
let keySystem:drm.MediaKeySystem = drm.createMediaKeySystem('com.clearplay.drm');
// Create a media key session.
let keySession:drm.MediaKeySession = keySystem.createMediaKeySession(drm.ContentProtectionLevel.CONTENT_PROTECTION_LEVEL_SW_CRYPTO);
// Flag indicating whether a secure video channel is used.
var secureVideoPath:boolean = false;
// Set the decryption configuration.
avPlayer.setDecryptionConfig(keySession, secureVideoPath);

getMediaKeySystemInfos11+

getMediaKeySystemInfos(): Array<drm.MediaKeySystemInfo>

Obtains the media key system information of the media asset that is being played. This API must be called after the [mediaKeySystemInfoUpdate event[(#onmediakeysysteminfoupdate11) is triggered.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Return value

Type Description
Array<drm.MediaKeySystemInfo> Array of MediaKeySystemInfo objects, each of which contains the uuid and pssh attributes.

Example

import drm from '@ohos.multimedia.drm'

const infos = avPlayer.getMediaKeySystemInfos();
console.info('GetMediaKeySystemInfos count: ' + infos.length);
for (var i = 0; i < infos.length; i++) {
  console.info('GetMediaKeySystemInfos uuid: ' + infos[i]["uuid"]);
  console.info('GetMediaKeySystemInfos pssh: ' + infos[i]["pssh"]);
}

seek9+

seek(timeMs: number, mode?:SeekMode): void

Seeks to the specified playback position. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the seek operation takes effect by subscribing to the seekDone event. This API is not supported in live mode.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
timeMs number Yes Position to seek to, in ms. The value range is [0, duration].
mode SeekMode No Seek mode based on the video I frame. The default value is SEEK_PREV_SYNC. Set this parameter only for video playback.

Example

let seekTime: number = 1000
avPlayer.seek(seekTime, media.SeekMode.SEEK_PREV_SYNC)

on('seekDone')9+

on(type: 'seekDone', callback: Callback<number>): void

Subscribes to the event to check whether the seek operation takes effect.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'seekDone' in this case. This event is triggered each time seek() is called.
callback Callback<number> Yes Callback invoked when the event is triggered. It reports the time position requested by the user.
For video playback, SeekMode may cause the actual position to be different from that requested by the user. The exact position can be obtained from the currentTime attribute. The time in this callback only means that the requested seek operation is complete.

Example

avPlayer.on('seekDone', (seekDoneTime:number) => {
  console.info('seekDone success,and seek time is:' + seekDoneTime)
})

off('seekDone')9+

off(type: 'seekDone'): void

Unsubscribes from the event that checks whether the seek operation takes effect.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'seekDone' in this case.

Example

avPlayer.off('seekDone')

setSpeed9+

setSpeed(speed: PlaybackSpeed): void

Sets the playback speed. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the setting takes effect by subscribing to the speedDone event. This API is not supported in live mode.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
speed PlaybackSpeed Yes Playback speed to set.

Example

avPlayer.setSpeed(media.PlaybackSpeed.SPEED_FORWARD_2_00_X)

on('speedDone')9+

on(type: 'speedDone', callback: Callback<number>): void

Subscribes to the event to check whether the playback speed is successfully set.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'speedDone' in this case. This event is triggered each time setSpeed() is called.
callback Callback<number> Yes Callback invoked when the event is triggered. It reports the speed set. For details, see PlaybackSpeed.

Example

avPlayer.on('speedDone', (speed:number) => {
  console.info('speedDone success,and speed value is:' + speed)
})

off('speedDone')9+

off(type: 'speedDone'): void

Unsubscribes from the event that checks whether the playback speed is successfully set.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'speedDone' in this case.

Example

avPlayer.off('speedDone')

setBitrate9+

setBitrate(bitrate: number): void

Sets the bit rate, which is valid only for HTTP Live Streaming (HLS) streams. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the setting takes effect by subscribing to the bitrateDone event. Note that the AVPlayer selects a proper bit rate based on the network connection speed.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
bitrate number Yes Bit rate to set. You can obtain the available bit rates of the current HLS stream by subscribing to the availableBitrates event. If the bit rate to set is not in the list of the available bit rates, the AVPlayer selects from the list the minimum bit rate that is closed to the bit rate to set. If the length of the available bit rate list obtained through the event is 0, no bit rate can be set and the bitrateDone callback will not be triggered.

Example

let bitrate: number = 96000
avPlayer.setBitrate(bitrate)

on('bitrateDone')9+

on(type: 'bitrateDone', callback: Callback<number>): void

Subscribes to the event to check whether the bit rate is successfully set.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'bitrateDone' in this case. This event is triggered each time setBitrate() is called.
callback function Yes Callback invoked when the event is triggered. It reports the effective bit rate.

Example

avPlayer.on('bitrateDone', (bitrate:number) => {
  console.info('bitrateDone success,and bitrate value is:' + bitrate)
})

off('bitrateDone')9+

off(type: 'bitrateDone'): void

Unsubscribes from the event that checks whether the bit rate is successfully set.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'bitrateDone' in this case.

Example

avPlayer.off('bitrateDone')

on('availableBitrates')9+

on(type: 'availableBitrates', callback: (bitrates: Array<number>) => void): void

Subscribes to available bit rates of HLS streams. This event is reported only after the AVPlayer switches to the prepared state.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'availableBitrates' in this case. This event is triggered once after the AVPlayer switches to the prepared state.
callback function Yes Callback invoked when the event is triggered. It returns an array that holds the available bit rates. If the array length is 0, no bit rate can be set.

Example

avPlayer.on('availableBitrates', (bitrates: Array<number>) => {
  console.info('availableBitrates success,and availableBitrates length is:' + bitrates.length)
})

off('availableBitrates')9+

off(type: 'availableBitrates'): void

Unsubscribes from available bit rates of HLS streams. This event is reported after prepare is called.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'availableBitrates' in this case.

Example

avPlayer.off('availableBitrates')

on('mediaKeySystemInfoUpdate')11+

on(type: 'mediaKeySystemInfoUpdate', callback: (mediaKeySystemInfo: Array<drm.MediaKeySystemInfo>) => void): void

Subscribes to media key system information changes.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'mediaKeySystemInfoUpdate' in this case. This event is triggered when the copyright protection information of the media asset being played changes.
callback function Yes Callback invoked when the event is triggered. It returns an array that holds the media key system information. For details, see MediaKeySystemInfo.

Example


import drm from './@ohos.multimedia.drm';

avPlayer.on('mediaKeySystemInfoUpdate', (mediaKeySystemInfo: Array<drm.MediaKeySystemInfo>) => {
    for (var i = 0; i < mediaKeySystemInfo.length; i++) {
      console.info('mediaKeySystemInfoUpdate happened uuid: ' + mediaKeySystemInfo[i]["uuid"]);
      console.info('mediaKeySystemInfoUpdate happened pssh: ' + mediaKeySystemInfo[i]["pssh"]);
    }
})

off('mediaKeySystemInfoUpdate')11+

off(type: 'mediaKeySystemInfoUpdate', callback?: (mediaKeySystemInfo: Array<drm.MediaKeySystemInfo>) => void): void;

Unsubscribes from media key system information changes.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'mediaKeySystemInfoUpdate' in this case.
callback function No Callback invoked when the event is triggered. It returns an array that holds the media key system information. For details, see MediaKeySystemInfo. If this parameter is specified, only the specified callback is unregistered. Otherwise, all callbacks associated with the specified event will be unregistered.

Example

avPlayer.off('mediaKeySystemInfoUpdate')

setVolume9+

setVolume(volume: number): void

Sets the volume. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the setting takes effect by subscribing to the volumeChange event.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
volume number Yes Relative volume. The value ranges from 0.00 to 1.00. The value 1.00 indicates the maximum volume (100%).

Example

let volume: number = 1.0
avPlayer.setVolume(volume)

on('volumeChange')9+

on(type: 'volumeChange', callback: Callback<number>): void

Subscribes to the event to check whether the volume is successfully set.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'volumeChange' in this case. This event is triggered each time setVolume() is called.
callback function Yes Callback invoked when the event is triggered. It reports the effective volume.

Example

avPlayer.on('volumeChange', (vol: number) => {
  console.info('volumeChange success,and new volume is :' + vol)
})

off('volumeChange')9+

off(type: 'volumeChange'): void

Unsubscribes from the event that checks whether the volume is successfully set.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'volumeChange' in this case.

Example

avPlayer.off('volumeChange')

on('endOfStream')9+

on(type: 'endOfStream', callback: Callback<void>): void

Subscribes to the event that indicates the end of the stream being played. If loop = true is set, the AVPlayer seeks to the beginning of the stream and plays the stream again. If loop is not set, the completed state is reported through the stateChange event.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'endOfStream' in this case. This event is triggered when the AVPlayer finishes playing the media asset.
callback Callback<void> Yes Callback invoked when the event is triggered.

Example

avPlayer.on('endOfStream', () => {
  console.info('endOfStream success')
})

off('endOfStream')9+

off(type: 'endOfStream'): void

Unsubscribes from the event that indicates the end of the stream being played.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'endOfStream' in this case.

Example

avPlayer.off('endOfStream')

on('timeUpdate')9+

on(type: 'timeUpdate', callback: Callback<number>): void

Subscribes to playback position changes. It is used to refresh the current position of the progress bar. By default, this event is reported every 100 ms. However, it is reported immediately upon a successful seek operation. The 'timeUpdate' event is not supported in live mode.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'timeUpdate' in this case.
callback function Yes Callback invoked when the event is triggered. It reports the current playback position, in ms.

Example

avPlayer.on('timeUpdate', (time:number) => {
  console.info('timeUpdate success,and new time is :' + time)
})

off('timeUpdate')9+

off(type: 'timeUpdate'): void

Unsubscribes from playback position changes.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'timeUpdate' in this case.

Example

avPlayer.off('timeUpdate')

on('durationUpdate')9+

on(type: 'durationUpdate', callback: Callback<number>): void

Subscribes to media asset duration changes. It is used to refresh the length of the progress bar. By default, this event is reported once when the AVPlayer switches to the prepared state. However, it can be repeatedly reported for special streams that trigger duration changes. The 'durationUpdate' event is not supported in live mode.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'durationUpdate' in this case.
callback function Yes Callback invoked when the event is triggered. It reports the media asset duration, in ms.

Example

avPlayer.on('durationUpdate', (duration: number) => {
  console.info('durationUpdate success,new duration is :' + duration)
})

off('durationUpdate')9+

off(type: 'durationUpdate'): void

Unsubscribes from media asset duration changes.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'durationUpdate' in this case.

Example

avPlayer.off('durationUpdate')

on('bufferingUpdate')9+

on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void

Subscribes to audio and video buffer changes. This subscription is supported only in network playback scenarios.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'bufferingUpdate' in this case.
callback function Yes Callback invoked when the event is triggered.
When BufferingInfoType is set to BUFFERING_PERCENT or CACHED_DURATION, value is valid. Otherwise, value is fixed at 0.

Example

avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
  console.info('bufferingUpdate success,and infoType value is:' + infoType + ', value is :' + value)
})

off('bufferingUpdate')9+

off(type: 'bufferingUpdate'): void

Unsubscribes from audio and video buffer changes.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'bufferingUpdate' in this case.

Example

avPlayer.off('bufferingUpdate')

on('startRenderFrame')9+

on(type: 'startRenderFrame', callback: Callback<void>): void

Subscribes to the event that indicates rendering starts for the first frame. This subscription is supported only in the video playback scenarios. This event only means that the playback service sends the first frame to the display module. The actual rendering effect depends on the rendering performance of the display service.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'startRenderFrame' in this case.
callback Callback<void> Yes Callback invoked when the event is triggered.

Example

avPlayer.on('startRenderFrame', () => {
  console.info('startRenderFrame success')
})

off('startRenderFrame')9+

off(type: 'startRenderFrame'): void

Unsubscribes from the event that indicates rendering starts for the first frame.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'startRenderFrame' in this case.

Example

avPlayer.off('startRenderFrame')

on('videoSizeChange')9+

on(type: 'videoSizeChange', callback: (width: number, height: number) => void): void

Subscribes to video size (width and height) changes. This subscription is supported only in the video playback scenarios. By default, this event is reported only once in the prepared state. However, it is also reported upon resolution changes in the case of HLS streams.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'videoSizeChange' in this case.
callback function Yes Callback invoked when the event is triggered. width indicates the video width, and height indicates the video height.

Example

avPlayer.on('videoSizeChange', (width: number, height: number) => {
  console.info('videoSizeChange success,and width is:' + width + ', height is :' + height)
})

off('videoSizeChange')9+

off(type: 'videoSizeChange'): void

Unsubscribes from video size changes.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'videoSizeChange' in this case.

Example

avPlayer.off('videoSizeChange')

on('audioInterrupt')9+

on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void

Subscribes to the audio interruption event. When multiple audio and video assets are played at the same time, this event is triggered based on the audio interruption mode audio.InterruptMode.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'audioInterrupt' in this case.
callback audio.InterruptEvent9+ Yes Callback invoked when the event is triggered.

Example

import audio from '@ohos.multimedia.audio';

avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => {
  console.info('audioInterrupt success,and InterruptEvent info is:' + info)
})

off('audioInterrupt')9+

off(type: 'audioInterrupt'): void

Unsubscribes from the audio interruption event.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'audioInterrupt' in this case.

Example

avPlayer.off('audioInterrupt')

on('audioOutputDeviceChangeWithInfo') 11+

on(type: 'audioOutputDeviceChangeWithInfo', callback: Callback<audio.AudioStreamDeviceChangeInfo>): void

Subscribes to audio stream output device changes and reasons. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'outputDeviceChangeWithInfo' is triggered when the output device is changed.
callback Callback<AudioStreamDeviceChangeInfo> Yes Callback used to return the output device descriptor of the current audio stream and the change reason.

Error codes

ID Error Message
401 Parameter error. Return by callback.

Example

import audio from '@ohos.multimedia.audio';

avPlayer.on('audioOutputDeviceChangeWithInfo', (data: audio.AudioStreamDeviceChangeInfo) => {
  console.info(`${JSON.stringify(data)}`);
});

off('audioOutputDeviceChangeWithInfo') 11+

off(type: 'audioOutputDeviceChangeWithInfo', callback?: Callback<audio.AudioStreamDeviceChangeInfo>): void

Unsubscribes from audio stream output device changes and reasons. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type. The event 'outputDeviceChange' is triggered when the audio output device is changed.
callback Callback<AudioStreamDeviceChangeInfo> No Callback used to return the output device descriptor of the current audio stream and the change reason.

Error codes

ID Error Message
401 Parameter error. Return by callback.

Example

avPlayer.off('audioOutputDeviceChangeWithInfo');

AVPlayerState9+

Enumerates the states of the AVPlayer. Your application can proactively obtain the AVPlayer state through the state attribute or obtain the reported AVPlayer state by subscribing to the stateChange event. For details about the rules for state transition, see Audio Playback.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Name Type Description
idle string The AVPlayer enters this state after createAVPlayer() or reset() is called.
In case createAVPlayer() is used, all attributes are set to their default values.
In case reset() is called, the url9+, fdSrc9+, or dataSrc10+ attribute and the loop attribute are reset, and other attributes are retained.
initialized string The AVPlayer enters this state after url9+ or fdSrc9+ attribute is set in the idle state. In this case, you can configure static attributes such as the window and audio.
prepared string The AVPlayer enters this state when prepare() is called in the initialized state. In this case, the playback engine has prepared the resources.
playing string The AVPlayer enters this state when play() is called in the prepared, paused, or completed state.
paused string The AVPlayer enters this state when pause() is called in the playing state.
completed string The AVPlayer enters this state when a media asset finishes playing and loop playback is not set (no loop = true). In this case, if play() is called, the AVPlayer enters the playing state and replays the media asset; if stop() is called, the AVPlayer enters the stopped state.
stopped string The AVPlayer enters this state when stop() is called in the prepared, playing, paused, or completed state. In this case, the playback engine retains the attributes but releases the memory resources. You can call prepare() to prepare the resources again, call reset() to reset the attributes, or call release() to destroy the playback engine.
released string The AVPlayer enters this state when release() is called. The playback engine associated with the AVPlayer instance is destroyed, and the playback process ends. This is the final state.
error string The AVPlayer enters this state when an irreversible error occurs in the playback engine. You can call reset() to reset the attributes or call release() to destroy the playback engine. For details on the errors, see Media Error Codes.
NOTE Relationship between the error state and the on('error') event
1. When the AVPlayer enters the error state, the on('error') event is triggered. You can obtain the detailed error information through this event.
2. When the AVPlayer enters the error state, the playback service stops. This requires the client to design a fault tolerance mechanism to call reset() or release().
3. The client receives on('error') event but the AVPlayer does not enter the error state. This situation occurs due to either of the following reasons:
Cause 1: The client calls an API in an incorrect state or passes in an incorrect parameter, and the AVPlayer intercepts the call. If this is the case, the client must correct its code logic.
Cause 2: A stream error is detected during playback. As a result, the container and decoding are abnormal for a short period of time, but continuous playback and playback control operations are not affected. If this is the case, the client does not need to design a fault tolerance mechanism.

AVFileDescriptor9+

Describes an audio and video file asset. It is used to specify a particular asset for playback based on its offset and length within a file.

System capability: SystemCapability.Multimedia.Media.Core

Name Type Mandatory Description
fd number Yes Resource handle, which is obtained by calling resourceManager.getRawFd.
offset number No Resource offset, which needs to be entered based on the preset asset information. The default value is 0. An invalid value causes a failure to parse audio and video assets.
length number No Resource length, which needs to be entered based on the preset asset information. The default value is the remaining bytes from the offset in the file. An invalid value causes a failure to parse audio and video assets.

AVDataSrcDescriptor10+

Defines the descriptor of an audio and video file, which is used in DataSource playback mode.
Use scenario: An application can create a playback instance and start playback before it finishes downloading the audio and video resources.

System capability: SystemCapability.Multimedia.Media.AVPlayer

Name Type Mandatory Description
fileSize number Yes Size of the file to play, in bytes. The value -1 indicates that the size is unknown. If fileSize is set to -1, the playback mode is similar to the live mode. In this mode, the seek and setSpeed operations cannot be performed, and the loop attribute cannot be set, indicating that loop playback is unavailable.
callback function Yes Callback used to fill in data.
- Function: callback: (buffer: ArrayBuffer, length: number, pos?:number) => number;
- buffer: memory to be filled. The value is of the ArrayBuffer type. This parameter is mandatory.
- length: maximum length of the memory to be filled. The value is of the number type. This parameter is mandatory.
- pos: position of the data to be filled in the file. The value is of the number type. This parameter is optional. When fileSize is set to -1, this parameter cannot be used.
- Return value: length of the data to be filled, which is of the number type.

SeekMode8+

Enumerates the video playback seek modes, which can be passed in the seek API.

System capability: SystemCapability.Multimedia.Media.Core

Name Value Description
SEEK_NEXT_SYNC 0 Seeks to the next key frame at the specified position. You are advised to use this value for the rewind operation.
SEEK_PREV_SYNC 1 Seeks to the previous key frame at the specified position. You are advised to use this value for the fast-forward operation.

PlaybackSpeed8+

Enumerates the video playback speeds, which can be passed in the setSpeed API.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Name Value Description
SPEED_FORWARD_0_75_X 0 Plays the video at 0.75 times the normal speed.
SPEED_FORWARD_1_00_X 1 Plays the video at the normal speed.
SPEED_FORWARD_1_25_X 2 Plays the video at 1.25 times the normal speed.
SPEED_FORWARD_1_75_X 3 Plays the video at 1.75 times the normal speed.
SPEED_FORWARD_2_00_X 4 Plays the video at 2.00 times the normal speed.

VideoScaleType9+

Enumerates the video scale modes.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Name Value Description
VIDEO_SCALE_TYPE_FIT 0 Default mode. The video will be stretched to fit the window.
VIDEO_SCALE_TYPE_FIT_CROP 1 The video will be stretched to fit the window, without changing its aspect ratio. The content may be cropped.

MediaDescription8+

Defines media information in key-value mode.

System capability: SystemCapability.Multimedia.Media.Core

Name Type Mandatory Description
[key: string] Object Yes For details about the key range supported and the object type and range of each key, see MediaDescriptionKey.

Example

import { BusinessError } from '@ohos.base';
import media from '@ohos.multimedia.media';

function printfItemDescription(obj: media.MediaDescription, key: string) {
  let property: Object = obj[key];
  console.info('audio key is ' + key); // Specify a key. For details about the keys, see [MediaDescriptionKey].
  console.info('audio value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [MediaDescriptionKey].
}

let avPlayer: media.AVPlayer | undefined = undefined;
media.createAVPlayer((err: BusinessError, player: media.AVPlayer) => {
  if(player != null) {
    avPlayer = player;
    console.info(`createAVPlayer success`);
    avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
      if (arrList != null) {
        for (let i = 0; i < arrList.length; i++) {
          printfItemDescription(arrList[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE);  // Print the MD_KEY_TRACK_TYPE value of each track.
        }
      } else {
        console.error(`audio getTrackDescription fail, error:${error}`);
      }
    });
  } else {
    console.error(`createAVPlayer fail, error message:${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.

For details about the audio and video recording demo, see Audio Recording and Video Recording.

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.

Attributes

System capability: SystemCapability.Multimedia.Media.AVRecorder

Name Type Readable Writable Description
state9+ AVRecorderState Yes No AVRecorder state.

prepare9+

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

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

Required permissions: ohos.permission.MICROPHONE

This permission is required only if audio recording is involved.

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.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

Name Type Mandatory Description
config AVRecorderConfig Yes Audio and 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. Return by callback.
5400102 Operate not permit. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@ohos.base';

// Configure the parameters based on those supported by the hardware device.
let avRecorderProfile: media.AVRecorderProfile = {
  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 avRecorderConfig: media.AVRecorderConfig = {
  audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
  videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
  profile : avRecorderProfile,
  url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: fd://45.
  rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error.
  location : { latitude : 30, longitude : 130 }
}

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

prepare9+

prepare(config: AVRecorderConfig): Promise<void>

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

Required permissions: ohos.permission.MICROPHONE

This permission is required only if audio recording is involved.

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.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

Name Type Mandatory Description
config AVRecorderConfig Yes Audio and 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. Return by promise.
5400102 Operate not permit. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@ohos.base';

// Configure the parameters based on those supported by the hardware device.
let avRecorderProfile: media.AVRecorderProfile = {
  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 avRecorderConfig: media.AVRecorderConfig = {
  audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
  videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
  profile : avRecorderProfile,
  url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: fd://45.
  rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error.
  location : { latitude : 30, longitude : 130 }
}

avRecorder.prepare(avRecorderConfig).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 video 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 the prepare() API is called.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

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

Error codes

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

ID Error Message
5400102 Operate not permit. Return by callback.
5400103 IO error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@ohos.base';
let surfaceID: string; // The surfaceID is transferred to the camera API to create a videoOutput instance.

avRecorder.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 video 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 the prepare() API is called.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 Operate not permit. Return by promise.
5400103 IO error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@ohos.base';
let surfaceID: string; // The surfaceID is transferred to the camera API to create a videoOutput instance.

avRecorder.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.

For audio-only recording, this API can be called only after the prepare() API is called. For video-only recording, this API can be called only after the getInputSurface() API is called.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 Operate not permit. Return by callback.
5400103 IO error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@ohos.base';

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

start9+

start(): Promise<void>

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

For audio-only recording, this API can be called only after the prepare() API is called. For video-only recording, this API can be called only after the getInputSurface() API is called.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 Operate not permit. Return by promise.
5400103 IO error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@ohos.base';

avRecorder.start().then(() => {
  console.info('start AVRecorder success');
}).catch((err: BusinessError) => {
  console.error('start AVRecorder 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 the start() API is called. You can call resume() to resume recording.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

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

Error codes

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

ID Error Message
5400102 Operate not permit. Return by callback.
5400103 IO error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@ohos.base';

avRecorder.pause((err: BusinessError) => {
  if (err == null) {
    console.info('pause AVRecorder success');
  } else {
    console.error('pause AVRecorder 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 the start() API is called. You can call resume() to resume recording.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 Operate not permit. Return by promise.
5400103 IO error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@ohos.base';

avRecorder.pause().then(() => {
  console.info('pause AVRecorder success');
}).catch((err: BusinessError) => {
  console.error('pause AVRecorder 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.

This API can be called only after the pause() API is called.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 Operate not permit. Return by callback.
5400103 IO error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@ohos.base';

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

resume9+

resume(): Promise<void>

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

This API can be called only after the pause() API is called.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 Operate not permit. Return by promise.
5400103 IO error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@ohos.base';

avRecorder.resume().then(() => {
  console.info('resume AVRecorder success');
}).catch((err: BusinessError) => {
  console.error('resume AVRecorder 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.

This API can be called only after the start() or pause() API is called.

For audio-only recording, you can call prepare() again for re-recording. For video-only recording or audio and video recording, you can call prepare() and getInputSurface() again for re-recording.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 Operate not permit. Return by callback.
5400103 IO error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@ohos.base';

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

stop9+

stop(): Promise<void>

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

This API can be called only after the start() or pause() API is called.

For audio-only recording, you can call prepare() again for re-recording. For video-only recording or audio and video recording, you can call prepare() and getInputSurface() again for re-recording.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 Operate not permit. Return by promise.
5400103 IO error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@ohos.base';

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

reset9+

reset(callback: AsyncCallback<void>): void

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

For audio-only recording, you can call prepare() again for re-recording. For video-only recording or audio and video recording, you can call prepare() and getInputSurface() again for re-recording.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 IO error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@ohos.base';

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

reset9+

reset(): Promise<void>

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

For audio-only recording, you can call prepare() again for re-recording. For video-only recording or audio and video recording, you can call prepare() and getInputSurface() again for re-recording.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 IO error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@ohos.base';

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

release9+

release(callback: AsyncCallback<void>): void

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

After the resources are released, you can no longer perform any operation on the AVRecorder instance.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 '@ohos.base';

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

release9+

release(): Promise<void>

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

After the resources are released, you can no longer perform any operation on the AVRecorder instance.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 '@ohos.base';

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

getCurrentAudioCapturerInfo11+

getCurrentAudioCapturerInfo(callback: AsyncCallback<audio.AudioCapturerChangeInfo>): void

Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result.

This API can be called only after the prepare() API is called. If this API is called after stop() is successfully called, an error is reported.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

Name Type Mandatory Description
callback AsyncCallback<audio.AudioCapturerChangeInfo> Yes Callback used to return the audio capturer information.

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

let currentCapturerInfo: audio.AudioCapturerChangeInfo;

avRecorder.getCurrentAudioCapturerInfo((err: BusinessError, capturerInfo: audio.AudioCapturerChangeInfo) => {
  if (err == null) {
    console.info('getCurrentAudioCapturerInfo success');
    currentCapturerInfo = capturerInfo;
  } else {
    console.error('getCurrentAudioCapturerInfo failed and error is ' + err.message);
  }
});

getCurrentAudioCapturerInfo11+

getCurrentAudioCapturerInfo(): Promise<audio.AudioCapturerChangeInfo>

Obtains the information about the current audio capturer. This API uses a promise to return the result.

This API can be called only after the prepare() API is called. If this API is called after stop() is successfully called, an error is reported.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Return value

Type Description
Promise<audio.AudioCapturerChangeInfo> Promise used to return the audio capturer information.

Error codes

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

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

Example

let currentCapturerInfo: audio.AudioCapturerChangeInfo;

avRecorder.getCurrentAudioCapturerInfo().then((capturerInfo: audio.AudioCapturerChangeInfo) => {
  console.info('getCurrentAudioCapturerInfo success');
  currentCapturerInfo = capturerInfo;
}).catch((err: BusinessError) => {
  console.error('getCurrentAudioCapturerInfo failed and catch error is ' + err.message);
});

getAudioCapturerMaxAmplitude11+

getAudioCapturerMaxAmplitude(callback: AsyncCallback<number>): void

Obtains the maximum amplitude of the current audio capturer. This API uses an asynchronous callback to return the result.

This API can be called only after the prepare() API is called. If this API is called after stop() is successfully called, an error is reported.

The return value is the maximum amplitude within the duration from the time the maximum amplitude is obtained last time to the current time. For example, if you have obtained the maximum amplitude at 1s and you call this API again at 2s, then the return value is the maximum amplitude within the duration from 1s to 2s.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

Name Type Mandatory Description
callback AsyncCallback<number> Yes Callback used to return the maximum amplitude.

Error codes

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

ID Error Message
5400102 Operation not allowed. Return by callback.
5400105 Service died. Return by callback.

Example

let maxAmplitude: number;

avRecorder.getAudioCapturerMaxAmplitude((err: BusinessError, amplitude: number) => {
  if (err == null) {
    console.info('getAudioCapturerMaxAmplitude success');
    maxAmplitude = amplitude;
  } else {
    console.error('getAudioCapturerMaxAmplitude failed and error is ' + err.message);
  }
});

getAudioCapturerMaxAmplitude11+

getAudioCapturerMaxAmplitude(): Promise<number>

Obtains the maximum amplitude of the current audio capturer. This API uses a promise to return the result.

This API can be called only after the prepare() API is called. If this API is called after stop() is successfully called, an error is reported.

The return value is the maximum amplitude within the duration from the time the maximum amplitude is obtained last time to the current time. For example, if you have obtained the maximum amplitude at 1s and you call this API again at 2s, then the return value is the maximum amplitude within the duration from 1s to 2s.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Return value

Type Description
Promise<number> Promise used to return the maximum amplitude.

Error codes

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

ID Error Message
5400102 Operation not allowed.
5400105 Service died. Return by promise.

Example

let maxAmplitude: number;

avRecorder.getAudioCapturerMaxAmplitude().then((amplitude: number) => {
  console.info('getAudioCapturerMaxAmplitude success');
  maxAmplitude = amplitude;
}).catch((err: BusinessError) => {
  console.error('getAudioCapturerMaxAmplitude failed and catch error is ' + err.message);
});

getAvailableEncoder11+

getAvailableEncoder(callback: AsyncCallback<Array<EncoderInfo>>): void

Obtains available encoders. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

Name Type Mandatory Description
callback AsyncCallback<Array<EncoderInfo>> Yes Callback used to return the information about the available encoders.

Error codes

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

ID Error Message
5400102 Operation not allowed. Return by callback.
5400105 Service died. Return by callback.

Example

let encoderInfo: media.EncoderInfo;

avRecorder.getAvailableEncoder((err: BusinessError, info: media.EncoderInfo) => {
  if (err == null) {
    console.info('getAvailableEncoder success');
    encoderInfo = info;
  } else {
    console.error('getAvailableEncoder failed and error is ' + err.message);
  }
});

getAvailableEncoder11+

getAvailableEncoder(): Promise<Array<EncoderInfo>>

Obtains available encoders. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Return value

Type Description
Promise<Array<EncoderInfo>> Promise used to return the information about the available encoders.

Error codes

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

ID Error Message
5400102 Operation not allowed.
5400105 Service died. Return by promise.

Example

let encoderInfo: media.EncoderInfo;

avRecorder.getAvailableEncoder().then((info: media.EncoderInfo) => {
  console.info('getAvailableEncoder success');
  encoderInfo = info;
}).catch((err: BusinessError) => {
  console.error('getAvailableEncoder failed and catch error is ' + err.message);
});

getAVRecorderConfig11+

getAVRecorderConfig(callback: AsyncCallback<AVRecorderConfig>): void

Obtains the real-time configuration of this AVRecorder. This API uses an asynchronous callback to return the result.

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

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

Name Type Mandatory Description
callback AsyncCallback<AVRecorderConfig> Yes Callback used to return the real-time configuration.

Error codes

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

ID Error Message
5400102 Operate not permit. Return by callback.
5400103 IO error. Return by callback.
5400105 Service died. Return by callback.

Example

import { BusinessError } from '@ohos.base';

let AVRecorderConfig: AVRecorderConfig;

avRecorder.getAVRecorderConfig((err: BusinessError, config: AVRecorderConfig) => {
  if (err == null) {
    console.info('getAVRecorderConfig success');
    AVRecorderConfig = config;
  } else {
    console.error('getAVRecorderConfig failed and error is ' + err.message);
  }
});

getAVRecorderConfig11+

getAVRecorderConfig(): Promise<AVRecorderConfig>;

Obtains the real-time configuration of this AVRecorder. This API uses a promise to return the result.

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

System capability: SystemCapability.Multimedia.Media.AVRecorder

Return value

Type Description
Promise<AVRecorderConfig> Promise used to return the real-time configuration.

Error codes

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

ID Error Message
5400102 Operate not permit. Return by promise.
5400103 IO error. Return by promise.
5400105 Service died. Return by promise.

Example

import { BusinessError } from '@ohos.base';

let AVRecorderConfig: AVRecorderConfig;

avRecorder.getAVRecorderConfig().then((config: AVRecorderConfig) => {
  console.info('getAVRecorderConfig success');
  AVRecorderConfig = config;
}).catch((err: BusinessError) => {
  console.error('getAVRecorderConfig failed and catch error is ' + err.message);
});

on('stateChange')9+

on(type: 'stateChange', callback: (state: AVRecorderState, reason: StateChangeReason) => void): void

Subscribes to AVRecorder state changes. An application can subscribe to only one AVRecorder state change event. When the application initiates multiple subscriptions to this event, the last subscription prevails.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'stateChange' in this case. This event can be triggered by both user operations and the system.
callback function Yes Callback invoked when the event is triggered. It reports the following information:
state: AVRecorderState, indicating the AVRecorder state.
reason: StateChangeReason, indicating the reason for the state transition.

Error codes

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

ID Error Message
5400103 IO error. Return by callback.
5400105 Service died. Return by callback.

Example

avRecorder.on('stateChange', async (state: media.AVRecorderState, reason: media.StateChangeReason) => {
  console.info('case state has changed, new state is :' + state + ',and new reason is : ' + reason);
});

off('stateChange')9+

off(type: 'stateChange'): void

Unsubscribes from AVRecorder state changes.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'stateChange' in this case. This event can be triggered by both user operations and the system.

Example

avRecorder.off('stateChange');

on('error')9+

on(type: 'error', callback: ErrorCallback): void

Subscribes to AVRecorder errors. This event is used only for error prompt and does not require the user to stop recording control. If the AVRecorderState is also switched to error, call reset() or [release()]release() to exit the recording.

An application can subscribe to only one AVRecorder error event. When the application initiates multiple subscriptions to this event, the last subscription prevails.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 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
5400101 No memory. Return by callback.
5400102 Operation not allowed. Return by callback.
5400103 I/O error. Return by callback.
5400104 Time out. Return by callback.
5400105 Service died. Return by callback.
5400106 Unsupport format. Return by callback.
5400107 Audio interrupted. Return by callback.

Example

import { BusinessError } from '@ohos.base';

avRecorder.on('error', (err: BusinessError) => {
  console.info('case avRecorder.on(error) called, errMessage is ' + err.message);
});

off('error')9+

off(type: 'error'): void

Unsubscribes from AVRecorder errors. After the unsubscription, your application can no longer receive AVRecorder errors.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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 recording.

Example

avRecorder.off('error');

on('audioCapturerChange')11+

on(type: 'audioCapturerChange', callback: Callback<audio.AudioCapturerChangeInfo>): void

Subscribes to audio capturer configuration changes. Any configuration change triggers the callback that returns the entire configuration information.

When the application initiates multiple subscriptions to this event, the last subscription prevails.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'audioCapturerChange' in this case.
callback Callback<audio.AudioCapturerChangeInfo> Yes Callback used to return the entire configuration information about the audio capturer.

Error codes

ID Error Message
401 Parameter error. Return by callback.

Example

let capturerChangeInfo: audio.AudioCapturerChangeInfo;

avRecorder.on('audioCapturerChange',  (audioCapturerChangeInfo: audio.AudioCapturerChangeInfo) => {
  console.info('audioCapturerChange success');
  capturerChangeInfo = audioCapturerChangeInfo;
});

off('audioCapturerChange')11+

off(type: 'audioCapturerChange'): void

Subscribes to audio capturer configuration changes.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'audioCapturerChange' in this case.

Example

avRecorder.off('audioCapturerChange');

AVRecorderState9+

Enumerates the AVRecorder states. You can obtain the state through the state attribute.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Name Type Description
idle string The AVRecorder enters this state after it is just created or the AVRecorder.reset() API is called when the AVRecorder is in any state except released. In this state, you can call AVRecorder.prepare() to set recording parameters.
prepared string The AVRecorder enters this state when the parameters are set. In this state, you can call AVRecorder.start() to start recording.
started string The AVRecorder enters this state when the recording starts. In this state, you can call AVRecorder.pause() to pause recording or call AVRecorder.stop() to stop recording.
paused string The AVRecorder enters this state when the recording is paused. In this state, you can call AVRecorder.resume() to continue recording or call AVRecorder.stop() to stop recording.
stopped string The AVRecorder enters this state when the recording stops. In this state, you can call AVRecorder.prepare() to set recording parameters so that the AVRecorder enters the prepared state again.
released string The AVRecorder enters this state when the recording resources are released. In this state, no operation can be performed. In any other state, you can call AVRecorder.release() to enter the released state.
error string The AVRecorder enters this state when an irreversible error occurs in the AVRecorder instance. In this state, the AVRecorder.on('error') event is reported, with the detailed error cause. In the error state, you must call AVRecorder.reset() to reset the AVRecorder instance or call AVRecorder.release() to release the resources.

AVRecorderConfig9+

Describes the audio and video recording parameters.

The audioSourceType and videoSourceType parameters are used to distinguish audio-only recording, video-only recording, and audio and video recording. For audio-only recording, set only audioSourceType. For video-only recording, set only videoSourceType. For audio and video recording, set both audioSourceType and videoSourceType.

System capability: SystemCapability.Multimedia.Media.AVRecorder

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

AVRecorderProfile9+

Describes the audio and video recording profile.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Name Type Mandatory Description
audioBitrate number No Audio encoding bit rate. This parameter is mandatory for audio recording. The value range is [8000 - 384000].
audioChannels number No Number of audio channels. This parameter is mandatory for audio recording. The value range is [1 - 2].
audioCodec CodecMimeType No Audio encoding format. This parameter is mandatory for audio recording. Only AUDIO_AAC is supported.
audioSampleRate number No Audio sampling rate. This parameter is mandatory for audio recording. The value range is [8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 96000].
fileFormat ContainerFormatType Yes Container format of a file. This parameter is mandatory.
videoBitrate number No Video encoding bit rate. This parameter is mandatory for video recording. The value range is [1 - 3000000].
videoCodec CodecMimeType No Video encoding format. This parameter is mandatory for video recording. Currently, VIDEO_AVC is supported.
videoFrameWidth number No Width of a video frame. This parameter is mandatory for video recording. The value range is [2 - 1920].
videoFrameHeight number No Height of a video frame. This parameter is mandatory for video recording. The value range is [2 - 1080].
videoFrameRate number No Video frame rate. This parameter is mandatory for video recording. The value range is [1 - 30].
isHdr11+ boolean No HDR encoding. This parameter is optional for video recording. The default value is false, and there is no requirement on the encoding format. When isHdr is set to true, the encoding format must be video/hevc.

AudioSourceType9+

Enumerates the audio source types for video recording.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Name Value Description
AUDIO_SOURCE_TYPE_DEFAULT 0 Default audio input source.
AUDIO_SOURCE_TYPE_MIC 1 Mic audio input source.

VideoSourceType9+

Enumerates the video source types for video recording.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Name Value Description
VIDEO_SOURCE_TYPE_SURFACE_YUV 0 The input surface carries raw data.
VIDEO_SOURCE_TYPE_SURFACE_ES 1 The input surface carries ES data.

ContainerFormatType8+

Enumerates the container format types (CFTs).

System capability: SystemCapability.Multimedia.Media.Core

Name Value Description
CFT_MPEG_4 'mp4' Video container format MP4.
CFT_MPEG_4A 'm4a' Audio container format M4A.

Location

Describes the geographical location of the recorded video.

System capability: SystemCapability.Multimedia.Media.Core

Name Type Mandatory Description
latitude number Yes Latitude of the geographical location.
longitude number Yes Longitude of the geographical location.

EncoderInfo11+

Describes the information about an encoder.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Name Type Readable Writable Description
mimeType CodecMimeType Yes No MIME type of the encoder.
type string Yes No Encoder type. The value audio means an audio encoder, and video means a video encoder.
bitRate Range Yes No Bit rate range of the encoder, with the minimum and maximum bit rates specified.
frameRate Range Yes No Video frame rate range, with the minimum and maximum frame rates specified. This parameter is available only for video encoders.
width Range Yes No Video frame width range, with the minimum and maximum widths specified. This parameter is available only for video encoders.
height Range Yes No Video frame height range, with the minimum and maximum heights specified. This parameter is available only for video encoders.
channels Range Yes No Number of audio channels for the audio capturer, with the minimum and maximum numbers of audio channels specified. This parameter is available only for audio encoders.
sampleRate Array<number> Yes No Audio sampling rate, including all available audio sampling rates. This parameter is available only for audio encoders.

Range11+

Describes a range.

System capability: SystemCapability.Multimedia.Media.AVRecorder

Name Type Readable Writable Description
min number Yes No Minimum value.
max number Yes No Maximum value.

AVMetadataExtractor11+

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

For details about the demo for obtaining audio or video metadata, see Obtaining Audio/Video Metadata.

Attributes

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

Name Type Readable Writable Description
fdSrc11+ AVFileDescriptor Yes Yes Media file descriptor, which specifies the data source. Before obtaining metadata, you must set the data source through either fdSrc or dataSrc.
Example:
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; }.
dataSrc11+ AVDataSrcDescriptor Yes Yes Streaming media resource descriptor, which specifies the data source. Before obtaining metadata, you must set the data source through either fdSrc or dataSrc.
When an application obtains a media file from the remote, you can set dataSrc to obtain the metadata before the application finishes the downloading.

fetchMetadata11+

fetchMetadata(callback: AsyncCallback<AVMetadata>): void

Obtains media metadata. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

Parameters

Name Type Mandatory Description
callback AsyncCallback<AVMetadata> Yes Callback used to return the result, which is an AVMetadata instance.

Error codes

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

ID Error Message
5400102 Operation not allowed. Returned by callback.
5400106 Unsupported format. Returned by callback.

Example

import { BusinessError } from '@ohos.base';
import media from '@ohos.multimedia.media';

let avMetadataExtractor: media.AVMetadataExtractor | undefined = undefined;

// Obtain the metadata.
media.createAVMetadataExtractor((err: BusinessError, extractor: media.AVMetadataExtractor) => {
  if(extractor != null){
    avMetadataExtractor = extractor;
    console.error(`createAVMetadataExtractor success`);
    avMetadataExtractor.fetchMetadata((error: BusinessError, metadata: media.AVMetadata) => {
      if (error) {
        console.error(`fetchMetadata callback failed, err = ${JSON.stringify(error)}`);
        return;
      }
      console.info(`fetchMetadata callback success, genre: ${metadata.genre}`);
    });
  } else {
    console.error(`createAVMetadataExtractor fail, error message:${err.message}`);
  }
});

fetchMetadata11+

fetchMetadata(): Promise<AVMetadata>

Obtains media metadata. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

Return value

Type Description
Promise<AVMetadata> Promise used to return the result, which is an AVMetadata instance.

Error codes

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

ID Error Message
5400102 Operation not allowed. Returned by promise.
5400106 Unsupported format. Returned by promise.

Example

import { BusinessError } from '@ohos.base';
import media from '@ohos.multimedia.media';

let avMetadataExtractor: media.AVMetadataExtractor | undefined = undefined;

// Obtain the metadata.
media.createAVMetadataExtractor((err: BusinessError, extractor: media.AVMetadataExtractor) => {
  if(extractor != null){
    avMetadataExtractor = extractor;
    console.error(`createAVMetadataExtractor success`);
    avMetadataExtractor.fetchMetadata().then((metadata: media.AVMetadata) => {
      console.info(`fetchMetadata callback success, genre: ${metadata.genre}`)
    }).catch((error: BusinessError) => {
      console.error(`fetchMetadata catchCallback, error message:${error.message}`);
    });
  } else {
    console.error(`createAVMetadataExtractor fail, error message:${err.message}`);
  }
});

fetchAlbumCover11+

fetchAlbumCover(callback: AsyncCallback<image.PixelMap>): void

Obtains the cover of the audio album. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

Parameters

Name Type Mandatory Description
callback AsyncCallback<image.PixelMap> Yes Callback used to return the album cover.

Error codes

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

ID Error Message
5400102 Operation not allowed. Return by callback.
5400106 Unsupported format. Returned by callback.

Example

import { BusinessError } from '@ohos.base';
import media from '@ohos.multimedia.media';
import image from '@ohos.multimedia.image';

let avMetadataExtractor: media.AVMetadataExtractor | undefined = undefined;
let pixel_map : image.PixelMap | undefined = undefined;

// Obtain the album cover.
media.createAVMetadataExtractor((err: BusinessError, extractor: media.AVMetadataExtractor) => {
  if(extractor != null){
    avMetadataExtractor = extractor;
    console.error(`createAVMetadataExtractor success`);
    avMetadataExtractor.fetchAlbumCover((error: BusinessError, pixelMap: image.PixelMap) => {
      if (error) {
        console.error(`fetchAlbumCover callback failed, error = ${JSON.stringify(error)}`);
        return;
      }
      pixel_map = pixelMap;
    });
  } else {
    console.error(`createAVMetadataExtractor fail, error message:${err.message}`);
  };
});

fetchAlbumCover11+

fetchAlbumCover(): Promise<image.PixelMap>

Obtains the cover of the audio album. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

Return value

Type Description
Promise<image.PixelMap> Promise used to return the album cover.

Error codes

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

ID Error Message
5400102 Operation not allowed. Returned by promise.
5400106 Unsupported format. Returned by promise.

Example

import { BusinessError } from '@ohos.base';
import media from '@ohos.multimedia.media';
import image from '@ohos.multimedia.image';

let avMetadataExtractor: media.AVMetadataExtractor | undefined = undefined;
let pixel_map : image.PixelMap | undefined = undefined;

// Obtain the album cover.
media.createAVMetadataExtractor((err: BusinessError, extractor: media.AVMetadataExtractor) => {
  if(extractor != null){
    avMetadataExtractor = extractor;
    console.error(`createAVMetadataExtractor success`);
    avMetadataExtractor.fetchAlbumCover().then((pixelMap: image.PixelMap) => {
      pixel_map = pixelMap;
    }).catch((error: BusinessError) => {
      console.error(`fetchAlbumCover catchCallback, error message:${error.message}`);
    });
  } else {
    console.error(`createAVMetadataExtractor fail, error message:${err.message}`);
  };
});

release11+

release(callback: AsyncCallback<void>): void

Releases this AVMetadataExtractor instance. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

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. Returned by callback.

Example

import { BusinessError } from '@ohos.base';
import media from '@ohos.multimedia.media';

let avMetadataExtractor: media.AVMetadataExtractor | undefined = undefined;

// Release the instance.
media.createAVMetadataExtractor((err: BusinessError, extractor: media.AVMetadataExtractor) => {
  if(extractor != null){
    avMetadataExtractor = extractor;
    console.error(`createAVMetadataExtractor success`);
    avMetadataExtractor.release((error: BusinessError) => {
      if (error) {
        console.error(`release failed, err = ${JSON.stringify(error)}`);
        return;
      }
      console.info(`release success.`);
    });
  } else {
    console.error(`createAVMetadataExtractor fail, error message:${err.message}`);
  };
});

release11+

release(): Promise<void>

Releases this AVMetadataExtractor instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

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. Returned by promise.

Example

import { BusinessError } from '@ohos.base';
import media from '@ohos.multimedia.media';

let avMetadataExtractor: media.AVMetadataExtractor | undefined = undefined;

// Release the instance.
media.createAVMetadataExtractor((err: BusinessError, extractor: media.AVMetadataExtractor) => {
  if(extractor != null){
    avMetadataExtractor = extractor;
    console.error(`createAVMetadataExtractor success`);
    avMetadataExtractor.release().then(() => {
      console.info(`release success.`);
    }).catch((error: BusinessError) => {
      console.error(`release catchCallback, error message:${error.message}`);
    });
  } else {
    console.error(`createAVMetadataExtractor fail, error message:${err.message}`);
  };
});

AVMetadata11+

Defines the audio and video metadata.

System capability: SystemCapability.Multimedia.Media.AVMetadataExtractor

Name Type Mandatory Description
album string No Title of the album.
albumArtist string No Artist of the album.
artist string No Artist of the media asset.
author string No Author of the media asset.
dateTime string No Time when the media asset is created.
dateTimeFormat string No Time when the media asset is created. The value is in the YYYY-MM-DD HH:mm:ss format.
composer string No Composer of the media asset.
duration string No Duration of the media asset.
genre string No Type or genre of the media asset.
hasAudio string No Whether the media asset contains audio.
hasVideo string No Whether the media asset contains a video.
mimeType string No MIME type of the media asset.
trackCount string No Number of tracks of the media asset.
sampleRate string No Audio sampling rate, in Hz.
title string No Title of the media asset.
videoHeight string No Video height, in px.
videoWidth string No Video width, in px.
videoOrientation string No Video rotation direction, in degrees.

media.createAudioPlayer(deprecated)

createAudioPlayer(): AudioPlayer

Creates an AudioPlayer instance in synchronous mode.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use createAVPlayer instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Return value

Type Description
AudioPlayer If the operation is successful, an AudioPlayer instance is returned; otherwise, null is returned. After the instance is created, you can start, pause, or stop audio playback.

Example

let audioPlayer: media.AudioPlayer = media.createAudioPlayer();

media.createVideoPlayer(deprecated)

createVideoPlayer(callback: AsyncCallback<VideoPlayer>): void

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

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use createAVPlayer instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

import { BusinessError } from '@ohos.base';

let videoPlayer: media.VideoPlayer;
media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
  if (video != null) {
    videoPlayer = video;
    console.info('video createVideoPlayer success');
  } else {
    console.error(`video createVideoPlayer fail, error:${error}`);
  }
});

media.createVideoPlayer(deprecated)

createVideoPlayer(): Promise<VideoPlayer>

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

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use createAVPlayer instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

import { BusinessError } from '@ohos.base';

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

media.createAudioRecorder(deprecated)

createAudioRecorder(): AudioRecorder

Creates an AudioRecorder instance to control audio recording. Only one AudioRecorder instance can be created per device.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use createAVRecorder instead.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Return value

Type Description
AudioRecorder If the operation is successful, an AudioRecorder instance is returned; otherwise, null is returned. The instance can be used to record audio.

Example

let audioRecorder: media.AudioRecorder = media.createAudioRecorder();

MediaErrorCode(deprecated)

Enumerates the media error codes.

NOTE

This enum is supported since API version 8 and deprecated since API version 11. You are advised to use Media Error Codes instead.

System capability: SystemCapability.Multimedia.Media.Core

Name Value Description
MSERR_OK 0 The operation is successful.
MSERR_NO_MEMORY 1 Failed to allocate memory. The system may have no available memory.
MSERR_OPERATION_NOT_PERMIT 2 No permission to perform the operation.
MSERR_INVALID_VAL 3 Invalid input parameter.
MSERR_IO 4 An I/O error occurs.
MSERR_TIMEOUT 5 The operation times out.
MSERR_UNKNOWN 6 An unknown error occurs.
MSERR_SERVICE_DIED 7 Invalid server.
MSERR_INVALID_STATE 8 The operation is not allowed in the current state.
MSERR_UNSUPPORTED 9 The operation is not supported in the current version.

AudioPlayer(deprecated)

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVPlayer instead.

Provides APIs to manage and play audio. Before calling any API in AudioPlayer, you must use createAudioPlayer() to create an AudioPlayer instance.

Attributes(deprecated)

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Name Type Readable Writable Description
src string Yes Yes Audio file URI. The mainstream audio formats (M4A, AAC, MP3, OGG, and WAV) are supported.
Example of supported URLs:
1. FD: fd://xx

2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
Required permissions: ohos.permission.READ_MEDIA or ohos.permission.INTERNET
fdSrc9+ AVFileDescriptor Yes Yes Description of the audio file. This attribute is required when audio assets of an application are continuously stored in a file.
Example:
Assume that a music file that stores continuous music assets consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent music file, use src=fd://xx.
loop boolean Yes Yes Whether to loop audio playback. The value true means to loop audio playback, and false means the opposite.
audioInterruptMode9+ audio.InterruptMode Yes Yes Audio interruption mode.
currentTime number Yes No Current audio playback position, in ms.
duration number Yes No Audio duration, in ms.
state AudioState Yes No Audio playback state. This state cannot be used as the condition for triggering the call of play(), pause(), or stop().

play(deprecated)

play(): void

Starts to play an audio asset. This API can be called only after the 'dataLoad' event is triggered.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVPlayer.play instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Example

audioPlayer.on('play', () => {    // Set the 'play' event callback.
  console.info('audio play success');
});
audioPlayer.play();

pause(deprecated)

pause(): void

Pauses audio playback.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVPlayer.pause instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Example

audioPlayer.on('pause', () => {    // Set the 'pause' event callback.
  console.info('audio pause success');
});
audioPlayer.pause();

stop(deprecated)

stop(): void

Stops audio playback.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVPlayer.stop instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Example

audioPlayer.on('stop', () => {    // Set the 'stop' event callback.
  console.info('audio stop success');
});
audioPlayer.stop();

reset(deprecated)

reset(): void

Resets the audio asset to be played.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use AVPlayer.reset instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Example

audioPlayer.on('reset', () => {    // Set the 'reset' event callback.
  console.info('audio reset success');
});
audioPlayer.reset();

seek(deprecated)

seek(timeMs: number): void

Seeks to the specified playback position.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVPlayer.seek instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Parameters

Name Type Mandatory Description
timeMs number Yes Position to seek to, in ms. The value range is [0, duration].

Example

audioPlayer.on('timeUpdate', (seekDoneTime: number) => {    // Set the 'timeUpdate' event callback.
  if (seekDoneTime == null) {
    console.error('audio seek fail');
    return;
  }
  console.info('audio seek success. seekDoneTime: ' + seekDoneTime);
});
audioPlayer.seek(30000); // Seek to 30000 ms.

setVolume(deprecated)

setVolume(vol: number): void

Sets the volume.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVPlayer.setVolume instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Parameters

Name Type Mandatory Description
vol number Yes Relative volume. The value ranges from 0.00 to 1.00. The value 1.00 indicates the maximum volume (100%).

Example

audioPlayer.on('volumeChange', () => {    // Set the 'volumeChange' event callback.
  console.info('audio volumeChange success');
});
audioPlayer.setVolume(1);    // Set the volume to 100%.

release(deprecated)

release(): void

Releases the audio playback resources.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVPlayer.release instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Example

audioPlayer.release();
audioPlayer = undefined;

getTrackDescription(deprecated)

getTrackDescription(callback: AsyncCallback<Array<MediaDescription>>): void

Obtains the audio track information. This API uses an asynchronous callback to return the result. It can be called only after the 'dataLoad' event is triggered.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.getTrackDescription instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Parameters

Name Type Mandatory Description
callback AsyncCallback<Array<MediaDescription>> Yes Callback used to return a MediaDescription array, which records the audio track information.

Example

import { BusinessError } from '@ohos.base';

audioPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
  if (arrList != null) {
    console.info('audio getTrackDescription success');
  } else {
    console.error(`audio getTrackDescription fail, error:${error}`);
  }
});

getTrackDescription(deprecated)

getTrackDescription(): Promise<Array<MediaDescription>>

Obtains the audio track information. This API uses a promise to return the result. It can be called only after the 'dataLoad' event is triggered.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.getTrackDescription instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Return value

Type Description
Promise<Array<MediaDescription>> Promise used to return a MediaDescription array, which records the audio track information.

Example

import { BusinessError } from '@ohos.base';

audioPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => {
  console.info('audio getTrackDescription success');
}).catch((error: BusinessError) => {
  console.error(`audio catchCallback, error:${error}`);
});

on('bufferingUpdate')(deprecated)

on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void

Subscribes to the audio buffering update event. This API works only under online playback.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.on('bufferingUpdate') instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'bufferingUpdate' in this case.
callback function Yes Callback invoked when the event is triggered.
When BufferingInfoType is set to BUFFERING_PERCENT or CACHED_DURATION, value is valid. Otherwise, value is fixed at 0.

Example

audioPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
  console.info('audio bufferingInfo type: ' + infoType);
  console.info('audio bufferingInfo value: ' + value);
});

on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange')(deprecated)

on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void

Subscribes to the audio playback events.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVPlayer.on('stateChange') instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type. The following events are supported:
- 'play': triggered when the play() API is called and audio playback starts.
- 'pause': triggered when the pause() API is called and audio playback is paused.
- 'stop': triggered when the stop() API is called and audio playback stops.
- 'reset': triggered when the reset() API is called and audio playback is reset.
- 'dataLoad': triggered when the audio data is loaded, that is, when the src attribute is configured.
- 'finish': triggered when the audio playback is finished.
- 'volumeChange': triggered when the setVolume() API is called and the playback volume is changed.
callback () => void Yes Callback invoked when the event is triggered.

Example

import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';

let audioPlayer: media.AudioPlayer = media.createAudioPlayer();  // Create an AudioPlayer instance.
audioPlayer.on('dataLoad', () => {            // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
  console.info('audio set source success');
  audioPlayer.play();                       // Start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => {                // Set the 'play' event callback.
  console.info('audio play success');
  audioPlayer.seek(30000);                  // Call the seek() API and trigger the 'timeUpdate' event callback.
});
audioPlayer.on('pause', () => {               // Set the 'pause' event callback.
  console.info('audio pause success');
  audioPlayer.stop();                       // Stop the playback and trigger the 'stop' event callback.
});
audioPlayer.on('reset', () => {               // Set the 'reset' event callback.
  console.info('audio reset success');
  audioPlayer.release();                    // Release the AudioPlayer instance.
  audioPlayer = undefined;
});
audioPlayer.on('timeUpdate', (seekDoneTime: number) => {  // Set the 'timeUpdate' event callback.
  if (seekDoneTime == null) {
    console.error('audio seek fail');
    return;
  }
  console.info('audio seek success, and seek time is ' + seekDoneTime);
  audioPlayer.setVolume(0.5);                // Set the volume to 50% and trigger the 'volumeChange' event callback.
});
audioPlayer.on('volumeChange', () => {         // Set the 'volumeChange' event callback.
  console.info('audio volumeChange success');
  audioPlayer.pause();                       // Pause the playback and trigger the 'pause' event callback.
});
audioPlayer.on('finish', () => {               // Set the 'finish' event callback.
  console.info('audio play finish');
  audioPlayer.stop();                        // Stop the playback and trigger the 'stop' event callback.
});
audioPlayer.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
  console.error(`audio error called, error: ${error}`);
});

// Set the FD (local playback) of the audio file selected by the user.
let fdPath = 'fd://';
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command.
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
fs.open(path).then((file) => {
  fdPath = fdPath + '' + file.fd;
  console.info('open fd success fd is' + fdPath);
  audioPlayer.src = fdPath;  // Set the src attribute and trigger the 'dataLoad' event callback.
}, (err: BusinessError) => {
  console.error('open fd failed err is' + err);
}).catch((err: BusinessError) => {
  console.error('open fd failed err is' + err);
});

on('timeUpdate')(deprecated)

on(type: 'timeUpdate', callback: Callback<number>): void

Subscribes to the 'timeUpdate' event. This event is reported every second when the audio playback is in progress.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVPlayer.on('timeUpdate') instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'timeUpdate' in this case.
The 'timeUpdate' event is triggered when the audio playback starts after an audio playback timestamp update.
callback Callback<number> Yes Callback invoked when the event is triggered. The input parameter is the updated timestamp.

Example

audioPlayer.on('timeUpdate', (newTime: number) => {    // Set the 'timeUpdate' event callback.
  if (newTime == null) {
    console.error('audio timeUpadate fail');
    return;
  }
  console.info('audio timeUpadate success. seekDoneTime: ' + newTime);
});
audioPlayer.play();    // The 'timeUpdate' event is triggered when the playback starts.

on('audioInterrupt')(deprecated)

on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void

Subscribes to the audio interruption event. For details, see audio.InterruptEvent.

NOTE

This API is supported in API version 9 and deprecated since API version 9. You are advised to use AVPlayer.on('audioInterrupt') instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'audioInterrupt' in this case.
callback function Yes Callback invoked when the event is triggered.

Example

import audio from '@ohos.multimedia.audio';

audioPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => {
  console.info('audioInterrupt success,and InterruptEvent info is:' + info)
})

on('error')(deprecated)

on(type: 'error', callback: ErrorCallback): void

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

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVPlayer.on('error') instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

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 audio playback.
callback ErrorCallback Yes Callback invoked when the event is triggered.

Example

import { BusinessError } from '@ohos.base';

audioPlayer.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
  console.error(`audio error called, error: ${error}`);
});
audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event.

AudioState(deprecated)

Enumerates the audio playback states. You can obtain the state through the state attribute.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVPlayerState instead.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Name Type Description
idle string No audio playback is in progress. The audio player is in this state after the 'dataload' or 'reset' event is triggered.
playing string Audio playback is in progress. The audio player is in this state after the 'play' event is triggered.
paused string Audio playback is paused. The audio player is in this state after the 'pause' event is triggered.
stopped string Audio playback is stopped. The audio player is in this state after the 'stop' event is triggered.
error string Audio playback is in the error state.

VideoPlayer(deprecated)

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer instead.

Provides APIs to manage and play video. Before calling any API of VideoPlayer, you must use createVideoPlayer() to create a VideoPlayer instance.

Attributes

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Name Type Readable Writable Description
url8+ string Yes Yes Video URL. The mainstream video formats (MP4, MPEG-TS, and MKV) are supported.
Example of supported URLs:
1. FD: fd://xx

2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
5. File type: file://xx
NOTE
WebM is no longer supported since API version 11.
fdSrc9+ AVFileDescriptor Yes Yes Description of a video file. This attribute is required when video assets of an application are continuously stored in a file.
Example:
Assume that a music file that stores continuous music assets consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent video file, use src=fd://xx.
loop8+ boolean Yes Yes Whether to loop video playback. The value true means to loop video playback, and false means the opposite.
videoScaleType9+ VideoScaleType Yes Yes Video scale type. The default value is VIDEO_SCALE_TYPE_FIT.
audioInterruptMode9+ audio.InterruptMode Yes Yes Audio interruption mode.
currentTime8+ number Yes No Current video playback position, in ms.
duration8+ number Yes No Video duration, in ms. The value -1 indicates the live mode.
state8+ VideoPlayState Yes No Video playback state.
width8+ number Yes No Video width, in px.
height8+ number Yes No Video height, in px.

setDisplaySurface(deprecated)

setDisplaySurface(surfaceId: string, callback: AsyncCallback<void>): void

Sets SurfaceId. This API uses an asynchronous callback to return the result.

*Note: SetDisplaySurface must be called between the URL setting and the calling of prepare. A surface must be set for video streams without audio. Otherwise, the calling of prepare fails.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.surfaceId instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
surfaceId string Yes Surface ID to set.
callback AsyncCallback<void> Yes Callback used to return the result.

Example

import { BusinessError } from '@ohos.base';

let surfaceId: string = '';
videoPlayer.setDisplaySurface(surfaceId, (err: BusinessError) => {
  if (err == null) {
    console.info('setDisplaySurface success!');
  } else {
    console.error('setDisplaySurface fail!');
  }
});

setDisplaySurface(deprecated)

setDisplaySurface(surfaceId: string): Promise<void>

Sets SurfaceId. This API uses a promise to return the result.

*Note: SetDisplaySurface must be called between the URL setting and the calling of prepare. A surface must be set for video streams without audio. Otherwise, the calling of prepare fails.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.surfaceId instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
surfaceId string Yes Surface ID to set.

Return value

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

Example

import { BusinessError } from '@ohos.base';

let surfaceId: string = '';
videoPlayer.setDisplaySurface(surfaceId).then(() => {
  console.info('setDisplaySurface success');
}).catch((error: BusinessError) => {
  console.error(`video catchCallback, error:${error}`);
});

prepare(deprecated)

prepare(callback: AsyncCallback<void>): void

Prepares for video playback. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.prepare instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.prepare((err: BusinessError) => {
  if (err == null) {
    console.info('prepare success!');
  } else {
    console.error('prepare fail!');
  }
});

prepare(deprecated)

prepare(): Promise<void>

Prepares for video playback. This API uses a promise to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.prepare instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.prepare().then(() => {
  console.info('prepare success');
}).catch((error: BusinessError) => {
  console.error(`video catchCallback, error:${error}`);
});

play(deprecated)

play(callback: AsyncCallback<void>): void

Starts to play video assets. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.play instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.play((err: BusinessError) => {
  if (err == null) {
    console.info('play success!');
  } else {
    console.error('play fail!');
  }
});

play(deprecated)

play(): Promise<void>

Starts to play video assets. This API uses a promise to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.play instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.play().then(() => {
  console.info('play success');
}).catch((error: BusinessError) => {
  console.error(`video catchCallback, error:${error}`);
});

pause(deprecated)

pause(callback: AsyncCallback<void>): void

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

NOTE This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.pause instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.pause((err: BusinessError) => {
  if (err == null) {
    console.info('pause success!');
  } else {
    console.error('pause fail!');
  }
});

pause(deprecated)

pause(): Promise<void>

Pauses video playback. This API uses a promise to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.pause instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.pause().then(() => {
  console.info('pause success');
}).catch((error: BusinessError) => {
  console.error(`video catchCallback, error:${error}`);
});

stop(deprecated)

stop(callback: AsyncCallback<void>): void

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

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.stop instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.stop((err: BusinessError) => {
  if (err == null) {
    console.info('stop success!');
  } else {
    console.error('stop fail!');
  }
});

stop(deprecated)

stop(): Promise<void>

Stops video playback. This API uses a promise to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.stop instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.stop().then(() => {
  console.info('stop success');
}).catch((error: BusinessError) => {
  console.error(`video catchCallback, error:${error}`);
});

reset(deprecated)

reset(callback: AsyncCallback<void>): void

Resets the video asset to be played. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.reset instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.reset((err: BusinessError) => {
  if (err == null) {
    console.info('reset success!');
  } else {
    console.error('reset fail!');
  }
});

reset(deprecated)

reset(): Promise<void>

Resets the video asset to be played. This API uses a promise to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.reset instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.reset().then(() => {
  console.info('reset success');
}).catch((error: BusinessError) => {
  console.error(`video catchCallback, error:${error}`);
});

seek(deprecated)

seek(timeMs: number, callback: AsyncCallback<number>): void

Seeks to the specified playback position. The previous key frame at the specified position is played. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.seek instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
timeMs number Yes Position to seek to, in ms. The value range is [0, duration].
callback AsyncCallback<number> Yes Callback used to return the result.

Example

import { BusinessError } from '@ohos.base';

let videoPlayer: media.VideoPlayer;
media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
  if (video != null) {
    videoPlayer = video;
    console.info('video createVideoPlayer success');
  } else {
    console.error(`video createVideoPlayer fail, error:${error}`);
  }
});

let seekTime: number = 5000;
videoPlayer.seek(seekTime, (err: BusinessError, result: number) => {
  if (err == null) {
    console.info('seek success!');
  } else {
    console.error('seek fail!');
  }
});

seek(deprecated)

seek(timeMs: number, mode:SeekMode, callback: AsyncCallback<number>): void

Seeks to the specified playback position. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.seek instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
timeMs number Yes Position to seek to, in ms. The value range is [0, duration].
mode SeekMode Yes Seek mode.
callback AsyncCallback<number> Yes Callback used to return the result.

Example

import { BusinessError } from '@ohos.base';

let videoPlayer: media.VideoPlayer | null = null;
media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
  if (video != null) {
    videoPlayer = video;
    console.info('video createVideoPlayer success');
  } else {
    console.error(`video createVideoPlayer fail, error:${error}`);
  }
});
let seekTime: number = 5000;
if (videoPlayer) {
  (videoPlayer as media.VideoPlayer).seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err: BusinessError, result: number) => {
    if (err == null) {
      console.info('seek success!');
    } else {
      console.error('seek fail!');
    }
  });
}

seek(deprecated)

seek(timeMs: number, mode?:SeekMode): Promise<number>

Seeks to the specified playback position. If mode is not specified, the previous key frame at the specified position is played. This API uses a promise to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.seek instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
timeMs number Yes Position to seek to, in ms. The value range is [0, duration].
mode SeekMode No Seek mode based on the video I frame. The default value is SEEK_PREV_SYNC.

Return value

Type Description
Promise<number> Promise used to return the playback position, in ms.

Example

import { BusinessError } from '@ohos.base';

let videoPlayer: media.VideoPlayer | null = null;
media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
  if (video != null) {
    videoPlayer = video;
    console.info('video createVideoPlayer success');
  } else {
    console.error(`video createVideoPlayer fail, error:${error}`);
  }
});
let seekTime: number = 5000;
if (videoPlayer) {
  (videoPlayer as media.VideoPlayer).seek(seekTime).then((seekDoneTime: number) => { // seekDoneTime indicates the position after the seek operation is complete.
    console.info('seek success');
  }).catch((error: BusinessError) => {
    console.error(`video catchCallback, error:${error}`);
  });

  (videoPlayer as media.VideoPlayer).seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime: number) => {
    console.info('seek success');
  }).catch((error: BusinessError) => {
    console.error(`video catchCallback, error:${error}`);
  });
}

setVolume(deprecated)

setVolume(vol: number, callback: AsyncCallback<void>): void

Sets the volume. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.setVolume instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
vol number Yes Relative volume. The value ranges from 0.00 to 1.00. The value 1.00 indicates the maximum volume (100%).
callback AsyncCallback<void> Yes Callback used to return the result.

Example

import { BusinessError } from '@ohos.base';

let vol: number = 0.5;
videoPlayer.setVolume(vol, (err: BusinessError) => {
  if (err == null) {
    console.info('setVolume success!');
  } else {
    console.error('setVolume fail!');
  }
});

setVolume(deprecated)

setVolume(vol: number): Promise<void>

Sets the volume. This API uses a promise to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.setVolume instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
vol number Yes Relative volume. The value ranges from 0.00 to 1.00. The value 1.00 indicates the maximum volume (100%).

Return value

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

Example

import { BusinessError } from '@ohos.base';

let vol: number = 0.5;
videoPlayer.setVolume(vol).then(() => {
  console.info('setVolume success');
}).catch((error: BusinessError) => {
  console.error(`video catchCallback, error:${error}`);
});

release(deprecated)

release(callback: AsyncCallback<void>): void

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

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.release instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.release((err: BusinessError) => {
  if (err == null) {
    console.info('release success!');
  } else {
    console.error('release fail!');
  }
});

release(deprecated)

release(): Promise<void>

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

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.release instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

import { BusinessError } from '@ohos.base';

videoPlayer.release().then(() => {
  console.info('release success');
}).catch((error: BusinessError) => {
  console.error(`video catchCallback, error:${error}`);
});

getTrackDescription(deprecated)

getTrackDescription(callback: AsyncCallback<Array<MediaDescription>>): void

Obtains the video track information. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.getTrackDescription instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
callback AsyncCallback<Array<MediaDescription>> Yes Callback used to return a MediaDescription array, which records the video track information.

Example

import { BusinessError } from '@ohos.base';

videoPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
  if ((arrList) != null) {
    console.info('video getTrackDescription success');
  } else {
    console.error(`video getTrackDescription fail, error:${error}`);
  }
});

getTrackDescription(deprecated)

getTrackDescription(): Promise<Array<MediaDescription>>

Obtains the video track information. This API uses a promise to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.getTrackDescription instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

Type Description
Promise<Array<MediaDescription>> Promise used to return a MediaDescription array, which records the video track information.

Example

import { BusinessError } from '@ohos.base';

videoPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => {
  if (arrList != null) {
    console.info('video getTrackDescription success');
  } else {
    console.error('video getTrackDescription fail');
  }
}).catch((error: BusinessError) => {
  console.error(`video catchCallback, error:${error}`);
});

setSpeed(deprecated)

setSpeed(speed: number, callback: AsyncCallback<number>): void

Sets the video playback speed. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.setSpeed instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
speed number Yes Video playback speed. For details, see PlaybackSpeed.
callback AsyncCallback<number> Yes Callback used to return the result.

Example

import { BusinessError } from '@ohos.base';

let videoPlayer: media.VideoPlayer | null = null;
media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
  if (video != null) {
    videoPlayer = video;
    console.info('video createVideoPlayer success');
  } else {
    console.error(`video createVideoPlayer fail, error:${error}`);
  }
});
let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X;
if (videoPlayer) {
  (videoPlayer as media.VideoPlayer).setSpeed(speed, (err: BusinessError, result: number) => {
    if (err == null) {
      console.info('setSpeed success!');
    } else {
      console.error('setSpeed fail!');
    }
  });
}

setSpeed(deprecated)

setSpeed(speed: number): Promise<number>

Sets the video playback speed. This API uses a promise to return the result.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.setSpeed instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
speed number Yes Video playback speed. For details, see PlaybackSpeed.

Return value

Type Description
Promise<number> Promise used to return playback speed. For details, see PlaybackSpeed.

Example

import { BusinessError } from '@ohos.base';

let videoPlayer: media.VideoPlayer | null = null;
media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
  if (video != null) {
    videoPlayer = video;
    console.info('video createVideoPlayer success');
  } else {
    console.error(`video createVideoPlayer fail, error:${error}`);
  }
});
let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X;
if (videoPlayer) {
  (videoPlayer as media.VideoPlayer).setSpeed(speed).then((result: number) => {
    console.info('setSpeed success');
  }).catch((error: BusinessError) => {
    console.error(`video catchCallback, error:${error}`);
  });
}

on('playbackCompleted')(deprecated)

on(type: 'playbackCompleted', callback: Callback<void>): void

Subscribes to the video playback completion event.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.on('stateChange') instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'playbackCompleted' in this case.
callback Callback<void> Yes Callback invoked when the event is triggered.

Example

videoPlayer.on('playbackCompleted', () => {
  console.info('playbackCompleted success!');
});

on('bufferingUpdate')(deprecated)

on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void

Subscribes to the video buffering update event. Only network playback supports this subscription.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.on('bufferingUpdate') instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'bufferingUpdate' in this case.
callback function Yes Callback invoked when the event is triggered.
When BufferingInfoType is set to BUFFERING_PERCENT or CACHED_DURATION, value is valid. Otherwise, value is fixed at 0.

Example

videoPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
  console.info('video bufferingInfo type: ' + infoType);
  console.info('video bufferingInfo value: ' + value);
});

on('startRenderFrame')(deprecated)

on(type: 'startRenderFrame', callback: Callback<void>): void

Subscribes to the frame rendering start event.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.on('startRenderFrame') instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'startRenderFrame' in this case.
callback Callback<void> Yes Callback invoked when the event is triggered.

Example

videoPlayer.on('startRenderFrame', () => {
  console.info('startRenderFrame success!');
});

on('videoSizeChanged')(deprecated)

on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void

Subscribes to the video width and height change event.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.on('videoSizeChange') instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'videoSizeChanged' in this case.
callback function Yes Callback invoked when the event is triggered. width indicates the video width, and height indicates the video height.

Example

videoPlayer.on('videoSizeChanged', (width: number, height: number) => {
  console.info('video width is: ' + width);
  console.info('video height is: ' + height);
});

on('audioInterrupt')(deprecated)

on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void

Subscribes to the audio interruption event. For details, see audio.InterruptEvent.

NOTE

This API is supported in API version 9 and deprecated since API version 9. You are advised to use AVPlayer.on('audioInterrupt') instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

Name Type Mandatory Description
type string Yes Event type, which is 'audioInterrupt' in this case.
callback function Yes Callback invoked when the event is triggered.

Example

import audio from '@ohos.multimedia.audio';

videoPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => {
  console.info('audioInterrupt success,and InterruptEvent info is:' + info)
})

on('error')(deprecated)

on(type: 'error', callback: ErrorCallback): void

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

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayer.on('error') instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

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 playback.
callback ErrorCallback Yes Callback invoked when the event is triggered.

Example

import { BusinessError } from '@ohos.base';

videoPlayer.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
  console.error(`video error called, error: ${error}`);
});
videoPlayer.url = 'fd://error';  // Set an incorrect URL to trigger the 'error' event.

VideoPlayState(deprecated)

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

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use AVPlayerState instead.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Name Type Description
idle string The video player is idle.
prepared string Video playback is being prepared.
playing string Video playback is in progress.
paused string Video playback is paused.
stopped string Video playback is stopped.
error string Video playback is in the error state.

AudioRecorder(deprecated)

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVRecorder instead.

Implements audio recording. Before calling any API of AudioRecorder, you must use createAudioRecorder() to create an AudioRecorder instance.

prepare(deprecated)

prepare(config: AudioRecorderConfig): void

Prepares for recording.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVRecorder.prepare instead.

Required permissions: ohos.permission.MICROPHONE

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Parameters

Name Type Mandatory Description
config AudioRecorderConfig Yes Audio recording parameters, including the audio output URI, encoding format, sampling rate, number of audio channels, and output format.

Example

let audioRecorderConfig: media.AudioRecorderConfig = {
  audioEncoder : media.AudioEncoder.AAC_LC,
  audioEncodeBitRate : 22050,
  audioSampleRate : 22050,
  numberOfChannels : 2,
  format : media.AudioOutputFormat.AAC_ADTS,
  uri : 'fd://1',       // The file must be created by the caller and granted with proper permissions.
  location : { latitude : 30, longitude : 130},
}
audioRecorder.on('prepare', () => {    // Set the 'prepare' event callback.
  console.info('prepare success');
});
audioRecorder.prepare(audioRecorderConfig);

start(deprecated)

start(): void

Starts audio recording. This API can be called only after the 'prepare' event is triggered.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVRecorder.start instead.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

audioRecorder.on('start', () => {    // Set the 'start' event callback.
  console.info('audio recorder start success');
});
audioRecorder.start();

pause(deprecated)

pause():void

Pauses audio recording. This API can be called only after the 'start' event is triggered.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVRecorder.pause instead.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

audioRecorder.on('pause', () => {    // Set the 'pause' event callback.
  console.info('audio recorder pause success');
});
audioRecorder.pause();

resume(deprecated)

resume():void

Resumes audio recording. This API can be called only after the 'pause' event is triggered.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVRecorder.resume instead.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

audioRecorder.on('resume', () => { // Set the 'resume' event callback.
  console.info('audio recorder resume success');
});
audioRecorder.resume();

stop(deprecated)

stop(): void

Stops audio recording.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVRecorder.stop instead.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

audioRecorder.on('stop', () => {    // Set the 'stop' event callback.
  console.info('audio recorder stop success');
});
audioRecorder.stop();

release(deprecated)

release(): void

Releases the audio recording resources.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVRecorder.release instead.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

audioRecorder.on('release', () => {    // Set the 'release' event callback.
  console.info('audio recorder release success');
});
audioRecorder.release();
audioRecorder = undefined;

reset(deprecated)

reset(): void

Resets audio recording.

Before resetting audio recording, you must call stop() to stop recording. After audio recording is reset, you must call prepare() to set the recording configurations for another recording.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVRecorder.reset instead.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

audioRecorder.on('reset', () => {    // Set the 'reset' event callback.
  console.info('audio recorder reset success');
});
audioRecorder.reset();

on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset')(deprecated)

on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void

Subscribes to the audio recording events.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVRecorder.on('stateChange') instead.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Parameters

Name Type Mandatory Description
type string Yes Event type. The following events are supported:
- 'prepare': triggered when the prepare() API is called and the audio recording parameters are set.
- 'start': triggered when the start() API is called and audio recording starts.
- 'pause': triggered when the pause() API is called and audio recording is paused.
- 'resume': triggered when the resume() API is called and audio recording is resumed.
- 'stop': triggered when the stop() API is called and audio recording stops.
- 'release': triggered when the release() API is called and the recording resources are released.
- 'reset': triggered when the reset() API is called and audio recording is reset.
callback ()=>void Yes Callback invoked when the event is triggered.

Example

import { BusinessError } from '@ohos.base';

let audioRecorder: media.AudioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance.
let audioRecorderConfig: media.AudioRecorderConfig = {
  audioEncoder : media.AudioEncoder.AAC_LC,
  audioEncodeBitRate : 22050,
  audioSampleRate : 22050,
  numberOfChannels : 2,
  format : media.AudioOutputFormat.AAC_ADTS,
  uri : 'fd://xx',  // The file must be created by the caller and granted with proper permissions.
  location : { latitude : 30, longitude : 130}
}
audioRecorder.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
  console.error(`audio error called, error: ${error}`);
});
audioRecorder.on('prepare', () => {  // Set the 'prepare' event callback.
  console.info('prepare success');
  audioRecorder.start();  // // Start recording and trigger the 'start' event callback.
});
audioRecorder.on('start', () => {  // Set the 'start' event callback.
  console.info('audio recorder start success');
});
audioRecorder.on('pause', () => {  // Set the 'pause' event callback.
  console.info('audio recorder pause success');
});
audioRecorder.on('resume', () => {  // Set the 'resume' event callback.
  console.info('audio recorder resume success');
});
audioRecorder.on('stop', () => {  // Set the 'stop' event callback.
  console.info('audio recorder stop success');
});
audioRecorder.on('release', () => {  // Set the 'release' event callback.
  console.info('audio recorder release success');
});
audioRecorder.on('reset', () => {  // Set the 'reset' event callback.
  console.info('audio recorder reset success');
});
audioRecorder.prepare(audioRecorderConfig)  // // Set recording parameters and trigger the 'prepare' event callback.

on('error')(deprecated)

on(type: 'error', callback: ErrorCallback): void

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

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVRecorder.on('error') instead.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

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 audio recording.
callback ErrorCallback Yes Callback invoked when the event is triggered.

Example

import { BusinessError } from '@ohos.base';

let audioRecorderConfig: media.AudioRecorderConfig = {
  audioEncoder : media.AudioEncoder.AAC_LC,
  audioEncodeBitRate : 22050,
  audioSampleRate : 22050,
  numberOfChannels : 2,
  format : media.AudioOutputFormat.AAC_ADTS,
  uri : 'fd://xx',   // The file must be created by the caller and granted with proper permissions.
  location : { latitude : 30, longitude : 130}
}
audioRecorder.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
  console.error(`audio error called, error: ${error}`);
});
audioRecorder.prepare(audioRecorderConfig);  // // Do not set any parameter in prepare and trigger the 'error' event callback.

AudioRecorderConfig(deprecated)

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use AVRecorderConfig instead.

Describes audio recording configurations.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Name Type Mandatory Description
audioEncoder AudioEncoder No Audio encoding format. The default value is AAC_LC.
Note: This parameter is deprecated since API version 8. Use audioEncoderMime instead.
audioEncodeBitRate number No Audio encoding bit rate. The default value is 48000.
audioSampleRate number No Audio sampling rate. The default value is 48000.
numberOfChannels number No Number of audio channels. The default value is 2.
format AudioOutputFormat No Audio output format. The default value is MPEG_4.
Note: This parameter is deprecated since API version 8. Use fileFormat instead.
location Location No Geographical location of the recorded audio.
uri string Yes Audio output URI. Supported: fd://xx (fd number)

The file must be created by the caller and granted with proper permissions.
audioEncoderMime8+ CodecMimeType No Container encoding format.
fileFormat8+ ContainerFormatType No Audio encoding format.

AudioEncoder(deprecated)

NOTE

This API is supported since API version 6 and deprecated since API version 8. You are advised to use CodecMimeType instead.

Enumerates the audio encoding formats.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Name Value Description
DEFAULT 0 Default encoding format.
This API is defined but not implemented yet.
AMR_NB 1 AMR-NB.
This API is defined but not implemented yet.
AMR_WB 2 Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is defined but not implemented yet.
AAC_LC 3 Advanced Audio Coding Low Complexity (AAC-LC).
HE_AAC 4 High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.

AudioOutputFormat(deprecated)

NOTE

This API is supported since API version 6 and deprecated since API version 8. You are advised to use ContainerFormatType instead.

Enumerates the audio output formats.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Name Value Description
DEFAULT 0 Default encapsulation format.
This API is defined but not implemented yet.
MPEG_4 2 MPEG-4.
AMR_NB 3 AMR_NB.
This API is defined but not implemented yet.
AMR_WB 4 AMR_WB.
This API is defined but not implemented yet.
AAC_ADTS 6 Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.