@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:

  • Audio and video playback, implemented by the AVPlayer9+ class. This class has integrated AudioPlayer6+ and VideoPlayer8+, with the state machine and error codes upgraded. It is recommended.
  • Audio and video recording, implemented by the AVRecorder9+ class. This class has integrated AudioRecorder6+ and VideoRecorder9+. It is recommended.
  • Audio playback, implemented by the AudioPlayer6+ class. It is deprecated. You are advised to use AVPlayer9+.
  • Video playback, implemented by the VideoPlayer8+ class. It is deprecated. You are advised to use AVPlayer9+.
  • Audio recording, implemented by the AudioRecorder6+ class. It is deprecated. You are advised to use AVRecorder9+.
  • Video recording, implemented by the VideoRecorder9+ class. It is deprecated. You are advised to use AVRecorder9+.

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.

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

let avPlayer

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

media.createAVPlayer9+

createAVPlayer(): Promise<AVPlayer>

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

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

let avPlayer

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

media.createAVRecorder9+

createAVRecorder(callback: AsyncCallback<AVRecorder>): void

Creates an AVRecorder instance. This API uses an asynchronous callback to return the result. Only one AVRecorder instance can be created per device.

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

let avRecorder

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

media.createAVRecorder9+

createAVRecorder(): Promise<AVRecorder>

Creates an AVRecorder instance. This API uses a promise to return the result. Only one AVRecorder instance can be created per device.

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

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

let avRecorder

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

media.createVideoRecorder9+

createVideoRecorder(callback: AsyncCallback<VideoRecorder>): void

Creates a VideoRecorder instance. This API uses an asynchronous callback to return the result. Only one VideoRecorder instance can be created per device.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

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

Error codes

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

ID Error Message
5400101 No memory. Return by callback.

Example

let videoRecorder

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

media.createVideoRecorder9+

createVideoRecorder(): Promise<VideoRecorder>

Creates a VideoRecorder instance. This API uses a promise to return the result. Only one VideoRecorder instance can be created per device.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

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

Error codes

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

ID Error Message
5400101 No memory. Return by promise.

Example

let videoRecorder

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

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.

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.
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 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 is a static attribute and can be set only when the AVPlayer is in the idle state.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, and WAV are supported.
Examples of supported URLs:
1. FD: fd://xx

2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
fdSrc9+ AVFileDescriptor Yes Yes FD of the media asset. It is a static attribute and 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.
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.
surfaceId9+ string Yes Yes Video window ID. By default, there is no video window. It is a static attribute and 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.
videoScaleType9+ VideoScaleType Yes Yes Video scaling type. The default value is VIDEO_SCALE_TYPE_FIT_CROP. 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.
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.
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 streaming scenarios, -1 is returned by default.
width9+ number Yes No Video width, in pixels. 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 pixels. 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, reason) => {
    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('unkown 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 the AVPlayer state 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 function Yes Callback used to return the error code ID and error message.

The AVPlayer provides the following error types:

ID Error Message Description
201 No Permission: No permission to perform the operation. The AVPlayer state is error.
401 Invalid Parameter: Incorrect input parameter, causing an invalid call.
801 Unsupport Capability: Unsupported API, causing an invalid call.
5400101 No Memory: Insufficient memory. The AVPlayer state is error.
5400102 Operate Not Permit: Unsupported operation in the current state, causing an invalid call.
5400103 IO Error: A stream exception is detected during playback. The AVPlayer state is error.
5400104 Network Timeout: The response times out due to a network error. The AVPlayer state is error.
5400105 Service Died: The playback process is dead. The AVPlayer state is error. In this case, you need to release the instance and then create an instance again.
5400106 Unsupport Format: Unsupported file format. The AVPlayer state is error.

Example

avPlayer.on('error', (error) => {
    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.

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

avPlayer.prepare((err) => {
    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.

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

avPlayer.prepare().then(() => {
    console.info('prepare success');
}, (err) => {
    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

avPlayer.play((err) => {
    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

avPlayer.play().then(() => {
    console.info('play success');
}, (err) => {
    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

avPlayer.pause((err) => {
    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

avPlayer.pause().then(() => {
    console.info('pause success');
}, (err) => {
    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

avPlayer.stop((err) => {
    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

avPlayer.stop().then(() => {
    console.info('stop success');
}, (err) => {
    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

avPlayer.reset((err) => {
    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

avPlayer.reset().then(() => {
    console.info('reset success');
}, (err) => {
    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

avPlayer.release((err) => {
    if (err == null) {
        console.info('reset 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

avPlayer.release().then(() => {
    console.info('release success');
}, (err) => {
    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.

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

printfDescription(obj) {
    for (let item in obj) {
        let property = obj[item];
        console.info('audio key is ' + item);
        console.info('audio value is ' + property);
    }
}

avPlayer.getTrackDescription((error, arrList) => {
    if ((arrList) != null) {
        for (let i = 0; i < arrList.length; i++) {
            printfDescription(arrList[i]);
        }
    } else {
        console.log(`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

let arrayDescription;

printfDescription(obj) {
    for (let item in obj) {
        let property = obj[item];
        console.info('audio key is ' + item);
        console.info('audio value is ' + property);
    }
}
avPlayer.getTrackDescription().then((arrList) => {
    if (arrList != null) {
        arrayDescription = arrList;
    } else {
        console.log('video getTrackDescription fail');
    }
}).catch((error) => {
    console.info(`video catchCallback, error:${error}`);
});
for (let i = 0; i < arrayDescription.length; i++) {
    printfDescription(arrayDescription[i]);
}

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.

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. Set this parameter only for video playback.

Example

let seekTime = 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.

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.

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

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')

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 = 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=1 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 1 second. However, it is reported immediately upon a successful seek operation.

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.

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) => {
    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')

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+ or fdSrc9+ attribute is 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 = 1). 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 Error Classification.
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.getRawFileDescriptor.
offset number Yes Resource offset, which needs to be entered based on the preset asset information. An invalid value causes a failure to parse audio and video assets.
length number Yes Resource length, which needs to be entered based on the preset asset information. An invalid value causes a failure to parse audio and video assets.

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

Example

import media from '@ohos.multimedia.media'
function printfItemDescription(obj, key) {
    let property = 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 audioPlayer = media.createAudioPlayer();
audioPlayer.getTrackDescription((error, arrList) => {
    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.log(`audio getTrackDescription fail, error:${error}`);
    }
});

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.

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

// Configure the parameters based on those supported by the hardware device.
let 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 = {
    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: eg.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) => {
    if (err == null) {
        console.info('prepare success');
    } else {
        console.info('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.

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

// Configure the parameters based on those supported by the hardware device.
let 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 = {
    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: eg.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) => {
    console.info('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

let surfaceID = null; // The surfaceID is transferred to the camera API to create a videoOutput instance.

avRecorder.getInputSurface((err, surfaceId) => {
    if (err == null) {
        console.info('getInputSurface success');
        surfaceID = surfaceId;
    } else {
        console.info('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

let surfaceID = null; // The surfaceID is transferred to the camera API to create a videoOutput instance.

avRecorder.getInputSurface().then((surfaceId) => {
    console.info('getInputSurface success');
    surfaceID = surfaceId;
}).catch((err) => {
    console.info('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

avRecorder.start((err) => {
    if (err == null) {
        console.info('start AVRecorder success');
    } else {
        console.info('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

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

avRecorder.pause((err) => {
    if (err == null) {
        console.info('pause AVRecorder success');
    } else {
        console.info('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

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

avRecorder.resume((err) => {
    if (err == null) {
        console.info('resume AVRecorder success');
    } else {
        console.info('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

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

avRecorder.stop((err) => {
    if (err == null) {
        console.info('stop AVRecorder success');
    } else {
        console.info('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

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

avRecorder.reset((err) => {
    if (err == null) {
        console.info('reset AVRecorder success');
    } else {
        console.info('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

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

avRecorder.release((err) => {
    if (err == null) {
        console.info('release AVRecorder success');
    } else {
        console.info('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

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

Example

avRecorder.on('stateChange', async (state, reason) => {
    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() 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
5400103 IO error. Return by callback.
5400105 Service died. Return by callback.

Example

avRecorder.on('error', (err) => {
    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.

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.off('error');

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 when the AVRecorder is just created or the reset() API is called in any non-released state. In this state, you can call prepare() to set recording parameters.
prepared string The AVRecorder enters this state when the parameters are set. In this state, you can call start() to start recording.
started string The AVRecorder enters this state when the recording starts. In this state, you can call pause() to pause the recording or call stop() to stop recording.
paused string The AVRecorder enters this state when the recording is paused. In this state, you can call resume() to continue the recording or call stop() to stop recording.
stopped string The AVRecorder enters this state when the recording stops. In this state, you can call prepare() to set recording parameters.
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 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 on('error') event is reported, with the detailed error cause. In the error state, you must call reset() to reset the AVRecorder instance or call release() to release the resources.

AVRecorderConfig9+

Describes the audio and video recording parameters.

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 only be 0, 90, 180, or 270.
location Location No Geographical location of the recorded video.

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.

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.
audioChannels number No Number of audio channels. This parameter is mandatory for audio recording.
audioCodec CodecMimeType No Audio encoding format. This parameter is mandatory for audio recording. Only AUDIO_AAC is supported.
audioSampleRate number No Audio sampling rate. This parameter is mandatory for audio recording.
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.
videoCodec CodecMimeType No Video encoding format. This parameter is mandatory for video recording. You need to query the encoding capabilities (including the encoding format and resolution) supported by the device.
videoFrameWidth number No Width of a video frame. This parameter is mandatory for video recording.
videoFrameHeight number No Height of a video frame. This parameter is mandatory for video recording.
videoFrameRate number No Video frame rate. This parameter is mandatory for video recording.

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.

VideoRecorder9+

NOTE

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

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

Attributes

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

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

prepare9+

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

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

Required permissions: ohos.permission.MICROPHONE

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

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

Error codes

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

ID Error Message
201 Permission denied. Return by callback.
401 Parameter error. Return by callback.
5400102 Operation not allowed. Return by callback.
5400105 Service died. Return by callback.

Example

// Configure the parameters based on those supported by the hardware device.
let videoProfile = {
    audioBitrate : 48000,
    audioChannels : 2,
    audioCodec : 'audio/mp4a-latm',
    audioSampleRate : 48000,
    fileFormat : 'mp4',
    videoBitrate : 2000000,
    videoCodec : 'video/avc',
    videoFrameWidth : 640,
    videoFrameHeight : 480,
    videoFrameRate : 30
}

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

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

prepare9+

prepare(config: VideoRecorderConfig): Promise<void>;

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

Required permissions: ohos.permission.MICROPHONE

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

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

Return value

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

Error codes

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

ID Error Message
201 Permission denied. Return by promise.
401 Parameter error. Return by promise.
5400102 Operation not allowed. Return by promise.
5400105 Service died. Return by promise.

Example

// Configure the parameters based on those supported by the hardware device.
let videoProfile = {
    audioBitrate : 48000,
    audioChannels : 2,
    audioCodec : 'audio/mp4a-latm',
    audioSampleRate : 48000,
    fileFormat : 'mp4',
    videoBitrate : 2000000,
    videoCodec : 'video/avc',
    videoFrameWidth : 640,
    videoFrameHeight : 480,
    videoFrameRate : 30
}

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

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

getInputSurface9+

getInputSurface(callback: AsyncCallback<string>): void;

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

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

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

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

Error codes

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

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

Example

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

getInputSurface9+

getInputSurface(): Promise<string>;

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

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

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

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

Error codes

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

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

Example

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

start9+

start(callback: AsyncCallback<void>): void;

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

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

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

Error codes

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

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

Example

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

start9+

start(): Promise<void>;

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

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

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

Error codes

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

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

Example

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

pause9+

pause(callback: AsyncCallback<void>): void;

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

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

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

Error codes

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

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

Example

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

pause9+

pause(): Promise<void>;

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

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

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

Error codes

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

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

Example

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

resume9+

resume(callback: AsyncCallback<void>): void;

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

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

Error codes

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

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

Example

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

resume9+

resume(): Promise<void>;

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

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

Error codes

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

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

Example

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

stop9+

stop(callback: AsyncCallback<void>): void;

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

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

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

Error codes

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

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

Example

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

stop9+

stop(): Promise<void>;

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

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

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

Error codes

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

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

Example

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

release9+

release(callback: AsyncCallback<void>): void;

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

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

Error codes

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

ID Error Message
5400105 Service died. Return by callback.

Example

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

release9+

release(): Promise<void>;

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

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

Error codes

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

ID Error Message
5400105 Service died. Return by callback.

Example

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

reset9+

reset(callback: AsyncCallback<void>): void;

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

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Parameters

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

Error codes

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

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

Example

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

reset9+

reset(): Promise<void>;

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

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Return value

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

Error codes

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

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

Example

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

on('error')9+

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

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

Parameters

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

Error codes

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

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

Example

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

VideoRecordState9+

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

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

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

VideoRecorderConfig9+

Describes the video recording parameters.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

Name Type Mandatory Description
audioSourceType AudioSourceType Yes Type of the audio source for video recording.
videoSourceType VideoSourceType Yes Type of the video source for video recording.
profile VideoRecorderProfile Yes Video recording profile.
rotation number No Rotation angle of the recorded video.
location Location No Geographical location of the recorded video.
url string Yes Video output URL. Supported: fd://xx (fd number)

VideoRecorderProfile9+

Describes the video recording profile.

System capability: SystemCapability.Multimedia.Media.VideoRecorder

System API: This is a system API.

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

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

let videoPlayer

media.createVideoPlayer((error, video) => {
   if (video != null) {
       videoPlayer = video;
       console.info('video createVideoPlayer success');
   } else {
       console.info(`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

let videoPlayer

media.createVideoPlayer().then((video) => {
   if (video != null) {
       videoPlayer = video;
       console.info('video createVideoPlayer success');
   } else {
       console.info('video createVideoPlayer fail');
   }
}).catch((error) => {
   console.info(`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 8 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, the AudioRecorder instance is returned; otherwise, null is returned. The instance can be used to record audio.

Example

let audioRecorder = media.createAudioRecorder();

MediaErrorCode(deprecated)

Enumerates the media error codes.

NOTE

This enum is supported since API version 8 and deprecated since API version 9. 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

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

play(): void

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

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Example

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

pause

pause(): void

Pauses audio playback.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Example

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

stop

stop(): void

Stops audio playback.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Example

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

reset7+

reset(): void

Resets the audio asset to be played.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Example

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

seek

seek(timeMs: number): void

Seeks to the specified playback position.

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) => {    // Set the 'timeUpdate' event callback.
    if (seekDoneTime == null) {
        console.info('audio seek fail');
        return;
    }
    console.log('audio seek success. seekDoneTime: ' + seekDoneTime);
});
audioPlayer.seek(30000); // Seek to 30000 ms.

setVolume

setVolume(vol: number): void

Sets the volume.

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.log('audio volumeChange success');
});
audioPlayer.setVolume(1);    // Set the volume to 100%.

release

release(): void

Releases the audio playback resources.

System capability: SystemCapability.Multimedia.Media.AudioPlayer

Example

audioPlayer.release();
audioPlayer = undefined;

getTrackDescription8+

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.

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

function printfDescription(obj) {
    for (let item in obj) {
        let property = obj[item];
        console.info('audio key is ' + item);
        console.info('audio value is ' + property);
    }
}

audioPlayer.getTrackDescription((error, arrList) => {
    if (arrList != null) {
        for (let i = 0; i < arrList.length; i++) {
            printfDescription(arrList[i]);
        }
    } else {
        console.log(`audio getTrackDescription fail, error:${error}`);
    }
});

getTrackDescription8+

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.

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

function printfDescription(obj) {
    for (let item in obj) {
        let property = obj[item];
        console.info('audio key is ' + item);
        console.info('audio value is ' + property);
    }
}
let arrayDescription = null
audioPlayer.getTrackDescription().then((arrList) => {
    if (arrList != null) {
        arrayDescription = arrList;
    } else {
        console.log('audio getTrackDescription fail');
    }
}).catch((error) => {
   console.info(`audio catchCallback, error:${error}`);
});

for (let i = 0; i < arrayDescription.length; i++) {
    printfDescription(arrayDescription[i]);
}

on('bufferingUpdate')8+

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

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

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, value) => {
    console.log('audio bufferingInfo type: ' + infoType);
    console.log('audio bufferingInfo value: ' + value);
});

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

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

Subscribes to the audio playback events.

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';

let 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) => {  // Set the 'timeUpdate' event callback.
    if (seekDoneTime == null) {
        console.info('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) => {           // Set the 'error' event callback.
    console.info(`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) => {
   console.info('open fd failed err is' + err);
}).catch((err) => {
   console.info('open fd failed err is' + err);
});

on('timeUpdate')

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.

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) => {    // Set the 'timeUpdate' event callback.
    if (newTime == null) {
        console.info('audio timeUpadate fail');
        return;
    }
    console.log('audio timeUpadate success. seekDoneTime: ' + newTime);
});
audioPlayer.play();    // The 'timeUpdate' event is triggered when the playback starts.

on('error')

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.

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

audioPlayer.on('error', (error) => {      // Set the 'error' event callback.
    console.info(`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, WebM, 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
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.
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 pixels.
height8+ number Yes No Video height, in pixels.

setDisplaySurface8+

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

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

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.

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

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

setDisplaySurface8+

setDisplaySurface(surfaceId: string): Promise<void>

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

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.

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

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

prepare8+

prepare(callback: AsyncCallback<void>): void

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

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

prepare8+

prepare(): Promise<void>

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

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

play8+

play(callback: AsyncCallback<void>): void;

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

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

play8+

play(): Promise<void>;

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

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

pause8+

pause(callback: AsyncCallback<void>): void

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

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

pause8+

pause(): Promise<void>

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

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

stop8+

stop(callback: AsyncCallback<void>): void

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

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

stop8+

stop(): Promise<void>

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

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

reset8+

reset(callback: AsyncCallback<void>): void

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

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

reset8+

reset(): Promise<void>

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

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

seek8+

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.

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

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

seek8+

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.

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 media from '@ohos.multimedia.media'
let seekTime = 5000;
videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err, result) => {
    if (err == null) {
        console.info('seek success!');
    } else {
        console.info('seek fail!');
    }
});

seek8+

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.

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.

Return value

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

Example

import media from '@ohos.multimedia.media'
let seekTime = 5000;
videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime indicates the position after the seek operation is complete.
    console.info('seek success');
}).catch((error) => {
   console.info(`video catchCallback, error:${error}`);
});

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

setVolume8+

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

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

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

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

setVolume8+

setVolume(vol: number): Promise<void>

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

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

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

release8+

release(callback: AsyncCallback<void>): void

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

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

release8+

release(): Promise<void>

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

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Return value

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

Example

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

getTrackDescription8+

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

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

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

function printfDescription(obj) {
    for (let item in obj) {
        let property = obj[item];
        console.info('video key is ' + item);
        console.info('video value is ' + property);
    }
}

videoPlayer.getTrackDescription((error, arrList) => {
    if ((arrList) != null) {
        for (let i = 0; i < arrList.length; i++) {
            printfDescription(arrList[i]);
        }
    } else {
        console.log(`video getTrackDescription fail, error:${error}`);
    }
});

getTrackDescription8+

getTrackDescription(): Promise<Array<MediaDescription>>

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

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

function printfDescription(obj) {
    for (let item in obj) {
        let property = obj[item];
        console.info('video key is ' + item);
        console.info('video value is ' + property);
    }
}

let arrayDescription;
videoPlayer.getTrackDescription().then((arrList) => {
    if (arrList != null) {
        arrayDescription = arrList;
    } else {
        console.log('video getTrackDescription fail');
    }
}).catch((error) => {
   console.info(`video catchCallback, error:${error}`);
});
for (let i = 0; i < arrayDescription.length; i++) {
    printfDescription(arrayDescription[i]);
}

setSpeed8+

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

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

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 media from '@ohos.multimedia.media'
let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X;

videoPlayer.setSpeed(speed, (err, result) => {
    if (err == null) {
        console.info('setSpeed success!');
    } else {
        console.info('setSpeed fail!');
    }
});

setSpeed8+

setSpeed(speed:number): Promise<number>

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

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 media from '@ohos.multimedia.media'
let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X;

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

on('playbackCompleted')8+

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

Subscribes to the video playback completion event.

System capability: SystemCapability.Multimedia.Media.VideoPlayer

Parameters

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

Example

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

on('bufferingUpdate')8+

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

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

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, value) => {
    console.log('video bufferingInfo type: ' + infoType);
    console.log('video bufferingInfo value: ' + value);
});

on('startRenderFrame')8+

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

Subscribes to the frame rendering start event.

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')8+

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

Subscribes to the video width and height change event.

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, height) => {
    console.log('video width is: ' + width);
    console.log('video height is: ' + height);
});

on('error')8+

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.

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

videoPlayer.on('error', (error) => {      // Set the 'error' event callback.
    console.info(`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

prepare(config: AudioRecorderConfig): void

Prepares for recording.

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 = {
    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.log('prepare success');
});
audioRecorder.prepare(audioRecorderConfig);

start

start(): void

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

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

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

pause

pause():void

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

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

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

resume

resume():void

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

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

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

stop

stop(): void

Stops audio recording.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

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

release

release(): void

Releases the audio recording resources.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

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

reset

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 parameters for another recording.

System capability: SystemCapability.Multimedia.Media.AudioRecorder

Example

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

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

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

Subscribes to the audio recording events.

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

let audioRecorder = media.createAudioRecorder();                                  // Create an AudioRecorder instance.
let 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) => {                                             // Set the 'error' event callback.
    console.info(`audio error called, error: ${error}`);
});
audioRecorder.on('prepare', () => {                                              // Set the 'prepare' event callback.
    console.log('prepare success');
    audioRecorder.start();                                                       // Start recording and trigger the 'start' event callback.
});
audioRecorder.on('start', () => {                                                 // Set the 'start' event callback.
    console.log('audio recorder start success');
});
audioRecorder.on('pause', () => {                                                 // Set the 'pause' event callback.
    console.log('audio recorder pause success');
});
audioRecorder.on('resume', () => {                                                 // Set the 'resume' event callback.
    console.log('audio recorder resume success');
});
audioRecorder.on('stop', () => {                                                 // Set the 'stop' event callback.
    console.log('audio recorder stop success');
});
audioRecorder.on('release', () => {                                                 // Set the 'release' event callback.
    console.log('audio recorder release success');
});
audioRecorder.on('reset', () => {                                                 // Set the 'reset' event callback.
    console.log('audio recorder reset success');
});
audioRecorder.prepare(audioRecorderConfig)                                       // Set recording parameters and trigger the 'prepare' event callback.

on('error')

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.

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

let 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) => {                                  // Set the 'error' event callback.
    console.info(`audio error called, error: ${error}`); 
});
audioRecorder.prepare(audioRecorderConfig);                            // Do no 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 Audio 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.