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.
API version 9 is a canary release for trial use. The APIs of this version may be unstable.
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 various media services covering audio and video, which provide the following capabilities:
- Audio playback (AudioPlayer)
- Video playback (VideoPlayer)
- Audio recording (AudioRecorder)
- Video recording (VideoRecorder)
The following capabilities will be provided in later versions: data source audio/video playback, audio/video encoding and decoding, container encapsulation and decapsulation, and media capability query.
Modules to Import
import media from '@ohos.multimedia.media';
media.createAudioPlayer
createAudioPlayer(): AudioPlayer
Creates an AudioPlayer instance in synchronous mode.
System capability: SystemCapability.Multimedia.Media.AudioPlayer
Return value
Type | Description |
---|---|
AudioPlayer | Returns the AudioPlayer instance if the operation is successful; returns null otherwise. After the instance is created, you can start, pause, or stop audio playback. |
Example
let audioPlayer = media.createAudioPlayer();
media.createVideoPlayer8+
createVideoPlayer(callback: AsyncCallback<VideoPlayer>): void
Creates a VideoPlayer instance in asynchronous mode. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | AsyncCallback<VideoPlayer> | Yes | Callback used to return the VideoPlayer instance created. |
Example
let videoPlayer
media.createVideoPlayer((error, video) => {
if (typeof(video) != 'undefined') {
videoPlayer = video;
console.info('video createVideoPlayer success');
} else {
console.info(`video createVideoPlayer fail, error:${error.message}`);
}
});
media.createVideoPlayer8+
createVideoPlayer(): Promise<VideoPlayer>
Creates a VideoPlayer instance in asynchronous mode. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Return value
Type | Description |
---|---|
Promise<VideoPlayer> | Promise used to return the VideoPlayer instance created. |
Example
let videoPlayer
media.createVideoPlayer().then((video) => {
if (typeof(video) != 'undefined') {
videoPlayer = video;
console.info('video createVideoPlayer success');
} else {
console.info('video createVideoPlayer fail');
}
}).catch((error) => {
console.info(`video catchCallback, error:${error.message}`);
});
media.createAudioRecorder
createAudioRecorder(): AudioRecorder
Creates an AudioRecorder instance to control audio recording.
System capability: SystemCapability.Multimedia.Media.AudioRecorder
Return value
Type | Description |
---|---|
AudioRecorder | Returns the AudioRecorder instance if the operation is successful; returns null otherwise. |
Example
let audiorecorder = media.createAudioRecorder();
media.createVideoRecorder9+
createVideoRecorder(callback: AsyncCallback<VideoRecorder>): void
Creates a VideoRecorder instance in asynchronous mode. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | AsyncCallback<VideoRecorder> | Yes | Callback used to return the VideoRecorder instance created. |
Example
let videoRecorder
media.createVideoRecorder((error, video) => {
if (typeof(video) != 'undefined') {
videoRecorder = video;
console.info('video createVideoRecorder success');
} else {
console.info(`video createVideoRecorder fail, error:${error.message}`);
}
});
media.createVideoRecorder9+
createVideoRecorder(): Promise<VideoRecorder>
Creates a VideoRecorder instance in asynchronous mode. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Return value
Type | Description |
---|---|
Promise<VideoRecorder> | Promise used to return the VideoRecorder instance created. |
Example
let videoRecorder
media.createVideoRecorder().then((video) => {
if (typeof(video) != 'undefined') {
videoRecorder = video;
console.info('video createVideoRecorder success');
} else {
console.info('video createVideoRecorder fail');
}
}).catch((error) => {
console.info(`video catchCallback, error:${error.message}`);
});
MediaErrorCode8+
Enumerates the media error codes.
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 this 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. |
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 milliseconds. |
AudioPlayer
Provides APIs to manage and play audio. Before calling an API of AudioPlayer, you must use createAudioPlayer() to create an AudioPlayer instance.
For details about the audio playback demo, see Audio Playback Development.
Attributes
System capability: SystemCapability.Multimedia.Media.AudioPlayer
Name | Type | Readable | Writable | Description |
---|---|---|---|---|
src | string | Yes | Yes | Audio media URI. The mainstream audio formats (MPEG-4, AAC, MPEG-3, OGG, and WAV) are supported. Example of supported URIs: 1. FD playback: fd://xx ![]() 2. HTTP network playback: http://xx 3. HLS network playback path (under development) Note: To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly. |
loop | boolean | Yes | Yes | Whether to loop audio playback. The value true means to loop audio playback, and false means the opposite. |
currentTime | number | Yes | No | Current audio playback position. |
duration | number | Yes | No | Audio duration. |
state | AudioState | Yes | No | Audio playback state. |
play
play(): void
Starts to play audio resources. 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
Switches the audio resource 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 milliseconds. |
Example
audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback.
if (typeof (seekDoneTime) == 'undefined') {
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 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 resource.
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 a 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 the audio track information obtained. |
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 (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
}
} else {
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
});
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 the audio track information obtained. |
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().then((arrlist) => {
if (typeof (arrlist) != 'undefined') {
arrayDescription = arrlist;
} else {
console.log('audio getTrackDescription fail');
}
}).catch((error) => {
console.info(`audio catchCallback, error:${error.message}`);
});
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.
System capability: SystemCapability.Multimedia.Media.AudioPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
type | string | Yes | Type of the event to subscribe to, which is 'bufferingUpdate' in this example. |
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 | Type of the event to subscribe to. The following events are supported: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange' - The 'play' event is triggered when the play() API is called and audio playback starts. - The 'pause' event is triggered when the pause() API is called and audio playback is paused. - The 'stop' event is triggered when the stop() API is called and audio playback stops. - The 'reset' event is triggered when the reset() API is called and audio playback is reset. - The 'dataLoad' event is triggered when the audio data is loaded, that is, when the src attribute is configured. - The 'finish' event is triggered when the audio playback is finished. - The 'volumeChange' event is triggered when the setVolume() API is called and the playback volume is changed. |
callback | () => void | Yes | Callback invoked when the event is triggered. |
Example
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 (typeof(seekDoneTime) == "undefined") {
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, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`);
});
// Set the FD (local playback) of the video 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';
fileIO.open(path).then(fdNumber) => {
fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
on('timeUpdate')
on(type: 'timeUpdate', callback: Callback<number>): void
Subscribes to the 'timeUpdate' event.
System capability: SystemCapability.Multimedia.Media.AudioPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
type | string | Yes | Type of the event to subscribe to, which is 'timeUpdate' in this API. The 'timeUpdate' event is triggered when the seek() API is called. |
callback | Callback<number> | Yes | Callback invoked when the event is triggered. The input parameter of the callback is the time when the seek operation is successful. |
Example
audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback.
if (typeof (seekDoneTime) == 'undefined') {
console.info('audio seek fail');
return;
}
console.log('audio seek success. seekDoneTime: ' + seekDoneTime);
});
audioPlayer.seek(30000); // Seek to 30000 ms.
on('error')
on(type: 'error', callback: ErrorCallback): void
Subscribes to the audio playback error event.
System capability: SystemCapability.Multimedia.Media.AudioPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
type | string | Yes | Type of the event to subscribe to, which is 'error' in this API. The 'error' 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, errName is ${error.name}`); // Print the error name.
console.info(`audio error called, errCode is ${error.code}`); // Print the error code.
console.info(`audio error called, errMessage is ${error.message}`);// Print the detailed description of the error type.
});
audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event.
AudioState
Enumerates the audio playback states. You can obtain the state through the state attribute.
System capability: SystemCapability.Multimedia.Media.AudioPlayer
Name | Type | Description |
---|---|---|
idle | string | The audio player is idle. |
playing | string | Audio playback is in progress. |
paused | string | Audio playback is paused. |
stopped | string | Audio playback is stopped. |
error8+ | string | Audio playback is in the error state. |
VideoPlayer8+
Provides APIs to manage and play video. Before calling an API of the VideoPlayer class, you must call createVideoPlayer() to create a VideoPlayer instance.
For details about the video playback demo, see Video Playback Development.
Attributes
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Name | Type | Readable | Writable | Description |
---|---|---|---|---|
url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported. Example of supported URIs: 1. FD playback: fd://xx ![]() 2. HTTP network playback: http://xx 3. HLS network playback path (under development) Note: To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly. |
loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value true means to loop video playback, and false means the opposite. |
currentTime8+ | number | Yes | No | Current video playback position. |
duration8+ | number | Yes | No | Video duration. The value -1 indicates the live streaming mode. |
state8+ | VideoPlayState | Yes | No | Video playback state. |
width8+ | number | Yes | No | Video width. |
height8+ | number | Yes | No | Video height. |
setDisplaySurface8+
setDisplaySurface(surfaceId: string, callback: AsyncCallback<void>): void
Sets SurfaceId. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
surfaceId | string | Yes | Surface ID to set. |
callback | function | Yes | Callback used to return the result. |
Example
videoPlayer.setDisplaySurface(surfaceId, (err) => {
if (typeof (err) == 'undefined') {
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.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
surfaceId | string | Yes | Surface ID to set. |
Return value
Type | Description |
---|---|
Promise |
Promise used to return the result. |
Example
videoPlayer.setDisplaySurface(surfaceId).then(() => {
console.info('setDisplaySurface success');
}).catch((error) => {
console.info(`video catchCallback, error:${error.message}`);
});
prepare8+
prepare(callback: AsyncCallback<void>): void
Prepares for video playback. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | function | Yes | Callback used to return the result. |
Example
videoPlayer.prepare((err) => {
if (typeof (err) == 'undefined') {
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.message}`);
});
play8+
play(callback: AsyncCallback<void>): void;
Starts to play video resources. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | function | Yes | Callback used to return the result. |
Example
videoPlayer.play((err) => {
if (typeof (err) == 'undefined') {
console.info('play success!');
} else {
console.info('play fail!');
}
});
play8+
play(): Promise<void>;
Starts to play video 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.play().then(() => {
console.info('play success');
}).catch((error) => {
console.info(`video catchCallback, error:${error.message}`);
});
pause8+
pause(callback: AsyncCallback<void>): void
Pauses video playback. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | function | Yes | Callback used to return the result. |
Example
videoPlayer.pause((err) => {
if (typeof (err) == 'undefined') {
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.message}`);
});
stop8+
stop(callback: AsyncCallback<void>): void
Stops video playback. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | function | Yes | Callback used to return the result. |
Example
videoPlayer.stop((err) => {
if (typeof (err) == 'undefined') {
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.message}`);
});
reset8+
reset(callback: AsyncCallback<void>): void
Switches the video resource to be played. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | function | Yes | Callback used to return the result. |
Example
videoPlayer.reset((err) => {
if (typeof (err) == 'undefined') {
console.info('reset success!');
} else {
console.info('reset fail!');
}
});
reset8+
reset(): Promise<void>
Switches the video resource 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.message}`);
});
seek8+
seek(timeMs: number, callback: AsyncCallback<number>): void
Seeks to the specified playback position. The next key frame at the specified position is played. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
timeMs | number | Yes | Position to seek to, in milliseconds. |
callback | function | Yes | Callback used to return the result. |
Example
videoPlayer.seek((seekTime, err) => {
if (typeof (err) == 'undefined') {
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 a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
timeMs | number | Yes | Position to seek to, in milliseconds. |
mode | SeekMode | Yes | Seek mode. |
callback | function | Yes | Callback used to return the result. |
Example
videoPlayer.seek((seekTime, seekMode, err) => {
if (typeof (err) == 'undefined') {
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 next 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 milliseconds. |
mode | SeekMode | No | Seek mode. |
Return value
Type | Description |
---|---|
Promise<void> | Promise used to return the result. |
Example
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.message}`);
});
videoPlayer.seek(seekTime, seekMode).then((seekDoneTime) => {
console.info('seek success');
}).catch((error) => {
console.info(`video catchCallback, error:${error.message}`);
});
setVolume8+
setVolume(vol: number, callback: AsyncCallback<void>): void
Sets the volume. This API uses a 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 indicates the maximum volume (100%). |
callback | function | Yes | Callback used to return the result. |
Example
videoPlayer.setVolume((vol, err) => {
if (typeof (err) == 'undefined') {
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 indicates the maximum volume (100%). |
Return value
Type | Description |
---|---|
Promise<void> | Promise used to return the result. |
Example
videoPlayer.setVolume(vol).then() => {
console.info('setVolume success');
}).catch((error) => {
console.info(`video catchCallback, error:${error.message}`);
});
release8+
release(callback: AsyncCallback<void>): void
Releases the video playback resource. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | function | Yes | Callback used to return the result. |
Example
videoPlayer.release((err) => {
if (typeof (err) == 'undefined') {
console.info('release success!');
} else {
console.info('release fail!');
}
});
release8+
release(): Promise<void>
Releases the video playback resource. 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.message}`);
});
getTrackDescription8+
getTrackDescription(callback: AsyncCallback<Array<MediaDescription>>): void
Obtains the video track information. This API uses a 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 the video track information obtained. |
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 (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
}
} else {
console.log(`video getTrackDescription fail, error:${error.message}`);
}
});
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 the video track information obtained. |
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 (typeof (arrlist) != 'undefined') {
arrayDescription = arrlist;
} else {
console.log('video getTrackDescription fail');
}
}).catch((error) => {
console.info(`video catchCallback, error:${error.message}`);
});
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 a 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 | function | Yes | Callback used to return the result. |
Example
videoPlayer.setSpeed((speed:number, err) => {
if (typeof (err) == 'undefined') {
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 the result. |
Example
videoPlayer.setSpeed(speed).then() => {
console.info('setSpeed success');
}).catch((error) => {
console.info(`video catchCallback, error:${error.message}`);
});
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 | Type of the event to subscribe to, which is 'playbackCompleted' in this example. |
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.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
type | string | Yes | Type of the event to subscribe to, which is 'bufferingUpdate' in this example. |
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 | Type of the event to subscribe to, which is 'startRenderFrame' in this example. |
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 | Type of the event to subscribe to, which is 'videoSizeChanged' in this example. |
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 the video playback error event.
System capability: SystemCapability.Multimedia.Media.VideoPlayer
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
type | string | Yes | Type of the event to subscribe to, which is 'error' in this API. The 'error' 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, errName is ${error.name}`); // Print the error name.
console.info(`video error called, errCode is ${error.code}`); // Print the error code.
console.info(`video error called, errMessage is ${error.message}`);// Print the detailed description of the error type.
});
videoPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event.
VideoPlayState8+
Enumerates the video playback states. You can obtain the state through the state attribute.
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. |
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. |
MediaDescription8+
[key : string] : Object
Defines media information in key-value mode.
System capability: SystemCapability.Multimedia.Media.Core
Name | Type | Description |
---|---|---|
key | string | Key of the media information. For details about the keys, see MediaDescriptionKey. |
value | any | Value of the key. For details about the values, see MediaDescriptionKey. |
Example
function printfItemDescription(obj, key) {
let property = obj[key];
console.info('audio key is ' + key);
console.info('audio value is ' + property);
}
audioPlayer.getTrackDescription((error, arrlist) => {
if (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) {
printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track.
}
} else {
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
});
AudioRecorder
Implements audio recording. Before calling an API of the AudioRecorder class, you must call createAudioRecorder() to create an AudioRecorder instance.
For details about the audio recording demo, see Audio Recording Development.
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 resource.
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 | Type of the event to subscribe to. The following events are supported: 'prepare'|'start'| 'pause' | 'resume' |'stop'|'release'|'reset' - The 'prepare' event is triggered when the prepare API is called and the audio recording parameters are set. - The 'start' event is triggered when the start API is called and audio recording starts. - The 'pause' event is triggered when the pause API is called and audio recording is paused. - The 'resume' event is triggered when the resume API is called and audio recording is resumed. - The 'stop' event is triggered when the stop API is called and audio recording stops. - The 'release' event is triggered when the release API is called and the recording resource is released. - The 'reset' event is 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, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`);
});
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 the audio recording error event.
System capability: SystemCapability.Multimedia.Media.AudioRecorder
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
type | string | Yes | Type of the event to subscribe to, which is 'error' in this API. The 'error' event is triggered when an error occurs during audio recording. |
callback | ErrorCallback | Yes | Callback invoked when the event is triggered. |
Example
audioRecorder.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`); // Print the error name.
console.info(`audio error called, errCode is ${error.code}`); // Print the error code.
console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type.
});
audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback.
AudioRecorderConfig
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. |
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. |
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. |
audioEncoderMime | CodecMimeType | No | Audio encoding format. |
AudioEncoder(deprecated)
NOTE This API is deprecated since API version 8. You are advised to use CodecMimeType instead.
Enumerates the audio encoding formats.
System capability: SystemCapability.Multimedia.Media.AudioRecorder
Name | Default 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 deprecated since API version 8. You are advised to use ContainerFormatType instead.
Enumerates the audio output formats.
System capability: SystemCapability.Multimedia.Media.AudioRecorder
Name | Default 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. |
VideoRecorder9+
Implements video recording. Before calling an API of the VideoRecorder class, you must call createVideoRecorder() to create a VideoRecorder instance.
For details about the video recording demo, see Video Recording Development.
Attributes
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Name | Type | Readable | Writable | Description |
---|---|---|---|---|
state8+ | VideoRecordState | Yes | No | Video recording state. |
prepare9+
prepare(config: VideoRecorderConfig, callback: AsyncCallback<void>): void;
Sets video recording parameters in asynchronous mode. This API uses a callback to return the result.
Required permissions: ohos.permission.MICROPHONE
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
config | VideoRecorderConfig | Yes | Video recording parameters to set. |
callback | AsyncCallback<void> | Yes | Callback used to return the result. |
Example
let videoProfile = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000,
fileFormat : 'mp4',
videoBitrate : 48000,
videoCodec : 'video/mp4v-es',
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
let videoRecorder = null;
let events = require('events');
let eventEmitter = new events.EventEmitter();
eventEmitter.on('prepare', () => {
videoRecorder.prepare(videoConfig, (err) => {
if (typeof (err) == 'undefined') {
console.info('prepare success');
} else {
console.info('prepare failed and error is ' + err.message);
}
});
});
media.createVideoRecorder((err, recorder) => {
if (typeof (err) == 'undefined' && typeof (recorder) != 'undefined') {
videoRecorder = recorder;
console.info('createVideoRecorder success');
eventEmitter.emit('prepare'); // Trigger the 'prepare' event.
} else {
console.info('createVideoRecorder failed and error is ' + err.message);
}
});
prepare9+
prepare(config: VideoRecorderConfig): Promise<void>;
Sets video recording parameters in asynchronous mode. This API uses a promise to return the result.
Required permissions: ohos.permission.MICROPHONE and ohos.permission.CAMERA
System capability: SystemCapability.Multimedia.Media.VideoRecorder
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. |
Example
let videoProfile = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000,
fileFormat : 'mp4',
videoBitrate : 48000,
videoCodec : 'video/mp4v-es',
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
let videoRecorder = null;
media.createVideoRecorder().then((recorder) => {
if (typeof (recorder) != 'undefined') {
videoRecorder = recorder;
console.info('createVideoRecorder success');
} else {
console.info('createVideoRecorder failed');
}
}).catch((err) => {
console.info('catch err error message is ' + err.message);
});
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 in asynchronous mode. This surface is provided for the caller. 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 is based on the system startup time.
This API can be called only after prepare() is called.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | AsyncCallback<string> | Yes | Callback used to obtain the result. |
Example
// asyncallback
let surfaceID = null; // Surface ID passed to the external system.
videoRecorder.getInputSurface((err, surfaceId) => {
if (typeof (err) == 'undefined') {
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 in asynchronous mode. This surface is provided for the caller. 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 is based on the system startup time.
This API can be called only after prepare() is called.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Return value
Type | Description |
---|---|
Promise<string> | Promise used to return the result. |
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 in asynchronous mode. This API uses a 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
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | AsyncCallback<void> | Yes | Callback used to return the result. |
Example
// asyncallback
videoRecorder.start((err) => {
if (typeof (err) == 'undefined') {
console.info('start videorecorder success');
} else {
console.info('start videorecorder failed and error is ' + err.message);
}
});
start9+
start(): Promise<void>;
Starts video recording in asynchronous mode. 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
Return value
Type | Description |
---|---|
Promise<void> | Promise used to return the result. |
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 in asynchronous mode. This API uses a 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
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | AsyncCallback<void> | Yes | Callback used to return the result. |
Example
// asyncallback
videoRecorder.pause((err) => {
if (typeof (err) == 'undefined') {
console.info('pause videorecorder success');
} else {
console.info('pause videorecorder failed and error is ' + err.message);
}
});
pause9+
pause(): Promise<void>;
Pauses video recording in asynchronous mode. 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
Return value
Type | Description |
---|---|
Promise<void> | Promise used to return the result. |
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 in asynchronous mode. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | AsyncCallback<void> | Yes | Callback used to return the result. |
Example
// asyncallback
videoRecorder.resume((err) => {
if (typeof (err) == 'undefined') {
console.info('resume videorecorder success');
} else {
console.info('resume videorecorder failed and error is ' + err.message);
}
});
resume9+
resume(): Promise<void>;
Resumes video recording in asynchronous mode. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Return value
Type | Description |
---|---|
Promise<void> | Promise used to return the result. |
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 in asynchronous mode. This API uses a callback to return the result.
To start another recording, you must call prepare() and getInputSurface() again.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | AsyncCallback<void> | Yes | Callback used to return the result. |
Example
// asyncallback
videoRecorder.stop((err) => {
if (typeof (err) == 'undefined') {
console.info('stop videorecorder success');
} else {
console.info('stop videorecorder failed and error is ' + err.message);
}
});
stop9+
stop(): Promise<void>;
Stops video recording in asynchronous mode. 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
Return value
Type | Description |
---|---|
Promise<void> | Promise used to return the result. |
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 resource in asynchronous mode. This API uses a callback to return the result.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | AsyncCallback<void> | Yes | Callback used to return the result. |
Example
// asyncallback
videoRecorder.release((err) => {
if (typeof (err) == 'undefined') {
console.info('release videorecorder success');
} else {
console.info('release videorecorder failed and error is ' + err.message);
}
});
release9+
release(): Promise<void>;
Releases the video recording resource in asynchronous mode. This API uses a promise to return the result.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Return value
Type | Description |
---|---|
Promise<void> | Promise used to return the result. |
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 in asynchronous mode. This API uses a callback to return the result.
To start another recording, you must call prepare() and getInputSurface() again.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | AsyncCallback<void> | Yes | Callback used to return the result. |
Example
// asyncallback
videoRecorder.reset((err) => {
if (typeof (err) == 'undefined') {
console.info('reset videorecorder success');
} else {
console.info('reset videorecorder failed and error is ' + err.message);
}
});
reset9+
reset(): Promise<void>;
Resets video recording in asynchronous mode. 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
Return value
Type | Description |
---|---|
Promise<void> | Promise used to return the result. |
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 the video recording error event.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
type | string | Yes | Type of the event to subscribe to, which is 'error' in this API. The 'error' event is triggered when an error occurs during video recording. |
callback | ErrorCallback | Yes | Callback invoked when the event is triggered. |
Example
videoRecorder.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`); // Print the error name.
console.info(`audio error called, errCode is ${error.code}`); // Print the error code.
console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type.
});
// This event is reported when an error occurs during the retrieval of videoRecordState.
VideoRecordState9+
Enumerates the video recording states. You can obtain the state through the state attribute.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
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
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)![]() The file must be created by the caller and granted with proper permissions. |
AudioSourceType9+
Enumerates the audio source types for video recording.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
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.VideoRecorder
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. |
VideoRecorderProfile9+
Describes the video recording profile.
System capability: SystemCapability.Multimedia.Media.VideoRecorder
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. |
ContainerFormatType8+
Enumerates the container format types (CFTs).
System capability: SystemCapability.Multimedia.Media.Core
Name | Value | Description |
---|---|---|
CFT_MPEG_4 | "mp4" | Video container format MPEG-4 . |
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. |