未验证 提交 e05aa9fa 编写于 作者: O openharmony_ci 提交者: Gitee

!2113 文档替换错误

Merge pull request !2113 from wusongqing/E0317
# Audio Playback Development # 音频播放开发指导
## When to Use ## 场景介绍
You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks. 音频播放的主要工作是将音频数据转码为可听见的音频模拟信号并通过输出设备进行播放,同时对播放任务进行管理。
**Figure 1** Playback status **图1** 音频播放状态机
![en-us_image_audio_state_machine](figures/en-us_image_audio_state_machine.png) ![zh-ch_image_audio_state_machine](figures/zh-ch_image_audio_state_machine.png)
**Figure 2** Layer 0 diagram of audio playback **图2** 音频播放零层图
![en-us_image_audio_player](figures/en-us_image_audio_player.png) ![zh-ch_image_audio_player](figures/zh-ch_image_audio_player.png)
## How to Develop ## 开发步骤
For details about the APIs used for audio playback, see [js-apis-media.md](../reference/apis/js-apis-media.md). 详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md)
### Full-Process Scenario ### 全流程场景
The full audio playback process includes creating an instance, setting the URI, playing audio, seeking to the playback position, setting the volume, pausing playback, obtaining track information, stopping playback, resetting resources, and releasing resources. 包含流程:创建实例,设置uri,播放音频,跳转播放位置,设置音量,暂停播放,获取轨道信息,停止播放,重置,释放资源等流程。
For details about the **src** media source input types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_attributes). AudioPlayer支持的src媒体源输入类型可参考:[src属性说明](../reference/apis/js-apis-media.md#audioplayer_属性)
```js ```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) { function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
console.info('audio set source success'); console.info('audio set source success');
// The playback page is ready. You can click the Play button to start the playback. //播放界面可切换至已准备好,可点击播放按钮进行播放状态
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { //设置'play'事件回调
console.info('audio play success'); console.info('audio play success');
// The Play button is changed to the pausable state. //将播放按钮切换至可暂停状态
}); });
audioPlayer.on('pause', () => { // Set the 'pause' event callback. audioPlayer.on('pause', () => { //设置'pause'事件回调
console.info('audio pause success'); console.info('audio pause success');
// The Play button is changed to the playable state. //将播放按钮切换至可播放状态
}); });
audioPlayer.on('stop', () => { // Set the 'stop' event callback. audioPlayer.on('stop', () => { //设置'stop'事件回调
console.info('audio stop success'); console.info('audio stop success');
// The playback stops, the playback progress bar returns to 0, and the Play button is changed to the playable state. //播放停止,播放进度条归零,播放按钮切换至可播放状态
}); });
audioPlayer.on('reset', () => { // Set the 'reset' event callback. audioPlayer.on('reset', () => { //设置'reset'事件回调
console.info('audio reset success'); console.info('audio reset success');
// You can reconfigure the src attribute to play another audio file. //需重新设置src属性后,可继续播放其他音频
}); });
audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback. audioPlayer.on('timeUpdate', (seekDoneTime) => {//设置'timeUpdate'事件回调
if (typeof(seekDoneTime) == 'undefined') { if (typeof(seekDoneTime) == 'undefined') {
console.info('audio seek fail'); console.info('audio seek fail');
return; return;
} }
console.info('audio seek success, and seek time is ' + seekDoneTime); console.info('audio seek success, and seek time is ' + seekDoneTime);
// The playback progress bar is updated to the seek position. //播放进度条更新到seek对应的位置
}); });
audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调
console.info('audio volumeChange success'); console.info('audio volumeChange success');
// Display the updated volume. //更新音量显示
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发
console.info('audio play finish'); console.info('audio play finish');
}); });
audioPlayer.on('error', (error) => { // Set the 'error' event callback. audioPlayer.on('error', (error) => { //设置'error'事件回调
console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`); console.info(`audio error called, errMessage is ${error.message}`);
...@@ -79,32 +76,21 @@ function printfDescription(obj) { ...@@ -79,32 +76,21 @@ function printfDescription(obj) {
} }
} }
// 1. Create an audioPlayer instance. //1、创建实例
let audioPlayer = media.createAudioPlayer(); let audioPlayer = media.createAudioPlayer();
SetCallBack(audioPlayer); // Set the event callbacks. SetCallBack(audioPlayer); //设置事件回调
// 2. Set the URI of the audio file. //2、用户选择音频,设置uri
let fdPath = 'fd://' audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; //设置src属性,并触发'dataLoad'事件回调
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; //3、播放音频
await fileIO.open(path).then(fdNumber) => { audioPlayer.play(); //需等待'dataLoad'事件回调完成后,才可调用play进行播放,触发'play'事件回调
fdPath = fdPath + '' + fdNumber; //4、跳转播放位置
console.info('open fd sucess fd is' + fdPath); audioPlayer.seek(30000); //触发'timeUpdate'事件回调,seek到30000ms处播放
}, (err) => { //5、设置音量
console.info('open fd failed err is' + err); audioPlayer.setVolume(0.5); //触发'volumeChange'事件回调
}),catch((err) => { //6、暂停播放
console.info('open fd failed err is' + err); audioPlayer.pause(); //触发'pause'事件回调,暂停播放
}); //7、获取轨道信息
audioPlayer.getTrackDescription((error, arrlist) => { //通过回调方式获取音频轨道信息
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
// 3. Play the audio.
audioPlayer.play(); // The play() method can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is triggered.
// 4. Seek to the playback position.
audioPlayer.seek(30000); // Trigger the 'timeUpdate' event callback, and seek to 30000 ms for playback.
// 5. Set the volume.
audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
// 6. Pause the playback.
audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
// 7. Obtain the track information.
audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
if (typeof (arrlist) != 'undefined') { if (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) { for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]); printfDescription(arrlist[i]);
...@@ -113,142 +99,87 @@ audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track ...@@ -113,142 +99,87 @@ audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track
console.log(`audio getTrackDescription fail, error:${error.message}`); console.log(`audio getTrackDescription fail, error:${error.message}`);
} }
}); });
// 8. Stop playback. //8、停止播放
audioPlayer.stop(); // Trigger the 'stop' event callback. audioPlayer.stop(); //触发'stop'事件回调
// 9. Reset the playback resources. //9、重置播放资源
audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. audioPlayer.reset(); //触发'reset'事件回调后,重新设置src属性,可完成切歌
// 10. Release the resource. //10、释放资源
audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer = undefined; audioPlayer = undefined;
``` ```
### Normal Playback Scenario ### 正常播放场景
```js ```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) { function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { //设置'play'事件回调
console.info('audio play success'); console.info('audio play success');
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发
console.info('audio play finish'); console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer = undefined; audioPlayer = undefined;
}); });
} }
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
SetCallBack(audioPlayer); // Set the event callbacks. SetCallBack(audioPlayer); //设置事件回调
/* Set the FD (local playback) of the audio file selected by the user. */ /* 用户选择音频,设置uri */
let fdPath = 'fd://' audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; //设置src属性,并触发'dataLoad'事件回调
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
await 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.
``` ```
### Switching to the Next Song ### 切歌场景
```js ```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) { function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { //设置'play'事件回调
console.info('audio play success'); console.info('audio play success');
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发
console.info('audio play finish'); console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer = undefined; audioPlayer = undefined;
}); });
} }
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
SetCallBack(audioPlayer); // Set the event callbacks. SetCallBack(audioPlayer); //设置事件回调
/* Set the FD (local playback) of the audio file selected by the user. */ /* 用户选择音频,设置uri */
let fdPath = 'fd://' audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; //设置src属性,并触发'dataLoad'事件回调
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; /* 播放一段时间后,下发切歌指令 */
await 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.
/* Send the instruction to switch to the next song after a period of time. */
audioPlayer.reset(); audioPlayer.reset();
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/next.mp3';
/* Set the FD (local playback) of the audio file selected by the user. */
let fdNextPath = 'fd://'
let nextPath = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
await fileIO.open(nextPath).then(fdNumber) => {
fdNextPath = fdNextPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdNextPath);
}, (err) => {
console.info('open fd failed err is' + err);
}),catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdNextPath;
``` ```
### Looping a Song ### 单曲循环场景
```js ```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) { function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { //设置'play'事件回调
console.info('audio play success'); console.info('audio play success');
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发
console.info('audio play finish'); console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer = undefined; audioPlayer = undefined;
}); });
} }
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
SetCallBack(audioPlayer); // Set the event callbacks. SetCallBack(audioPlayer); //设置事件回调
/* 用户选择音频,设置uri */
/* Set the FD (local playback) of the audio file selected by the user. */ audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; //设置src属性,并触发'dataLoad'事件回调
let fdPath = 'fd://' audioPlayer.loop = true; //设置循环播放属性
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; ```
await fileIO.open(path).then(fdNumber) => { \ No newline at end of file
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.
audioPlayer.loop = true; // Set the loop playback attribute.
```
# Audio Recording Development # 音频录制开发指导
## When to Use ## 场景介绍
During audio recording, audio signals are captured, encoded, and saved to files. You can specify parameters such as the sampling rate, number of audio channels, encoding format, encapsulation format, and file path for audio recording. 音频录制的主要工作是捕获音频信号,完成音频编码并保存到文件中,帮助开发者轻松实现音频录制功能。它允许调用者指定音频录制的采样率、声道数、编码格式、封装格式、文件路径等参数。
**Figure 1** Audio recording state transition **图1** 音频录制状态机
![en-us_image_audio_recorder_state_machine](figures/en-us_image_audio_recorder_state_machine.png) ![zh-ch_image_audio_recorder_state_machine](figures/zh-ch_image_audio_recorder_state_machine.png)
**Figure 2** Layer 0 diagram of audio recording **图2** 音频录制零层图
![en-us_image_audio_recorder_zero](figures/en-us_image_audio_recorder_zero.png) ![zh-ch_image_audio_recorder_zero](figures/zh-ch_image_audio_recorder_zero.png)
## How to Develop ## 开发步骤
For details about the APIs used for audio recording, see [js-apis-media.md](../reference/apis/js-apis-media.md). 详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md)
### Full-Process Scenario ### 全流程场景
The full audio recording process includes creating an instance, setting recording parameters, starting, pausing, resuming, and stopping recording, and releasing resources. 包含流程:创建实例,设置录制参数,录制音频,暂停录制,恢复录制,停止录制,释放资源等流程。
```js ```js
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
function SetCallBack(audioRecorder) { function SetCallBack(audioRecorder) {
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. audioRecorder.on('prepare', () => { // 设置'prepare'事件回调
console.log('prepare success'); console.log('prepare success');
// The recording page is ready. You can click the Record button to start recording. // 录制界面可切换至已准备好,可点击录制按钮进行录制
}); });
audioRecorder.on('start', () => { // Set the 'start' event callback. audioRecorder.on('start', () => { // 设置'start'事件回调
console.log('audio recorder start success'); console.log('audio recorder start success');
// The Record button is changed to the pausable state. // 将录制按钮切换至可暂停状态
}); });
audioRecorder.on('pause', () => { // Set the 'pause' event callback. audioRecorder.on('pause', () => { // 设置'pause'事件回调
console.log('audio recorder pause success'); console.log('audio recorder pause success');
// The Record button is changed to the recordable state. // 将录制按钮切换至可录制状态
}); });
audioRecorder.on('resume', () => { // Set the 'resume' event callback. audioRecorder.on('resume', () => { // 设置'resume'事件回调
console.log('audio recorder resume success'); console.log('audio recorder resume success');
// The Record button is changed to the pausable state. // 将录制按钮切换至可暂停状态
}); });
audioRecorder.on('stop', () => { // Set the 'stop' event callback. audioRecorder.on('stop', () => { // 设置'stop'事件回调
console.log('audio recorder stop success'); console.log('audio recorder stop success');
}); });
audioRecorder.on('release', () => { // Set the 'release' event callback. audioRecorder.on('release', () => { // 设置'release'事件回调
console.log('audio recorder release success'); console.log('audio recorder release success');
}); });
audioRecorder.on('reset', () => { // Set the 'reset' event callback. audioRecorder.on('reset', () => { // 设置'reset'事件回调
console.log('audio recorder reset success'); console.log('audio recorder reset success');
// You need to reset the recording parameters for another recording. // 需要重新设置录制参数才能再次录制
}); });
audioRecorder.on('error', (error) => { // Set the 'error' event callback. audioRecorder.on('error', (error) => { // 设置'error'事件回调
console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`); console.info(`audio error called, errMessage is ${error.message}`);
}); });
} }
// pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Movies/01.mp3. // 1.创建实例
// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA.
async function getFd(pathName) {
let displayName = pathName;
const mediaTest = mediaLibrary.getMediaLibrary();
let fileKeyObj = mediaLibrary.FileKey;
let mediaType = mediaLibrary.MediaType.VIDEO;
let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO);
let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath);
if (dataUri != undefined) {
let args = dataUri.id.toString();
let fetchOp = {
selections : fileKeyObj.ID + "=?",
selectionArgs : [args],
}
let fetchFileResult = await mediaTest.getFileAssets(fetchOp);
let fileAsset = await fetchFileResult.getAllObject();
let fdNumber = await fileAsset[0].open('Rw');
fdNumber = "fd://" + fdNumber.toString();
testFdNumber = fdNumber;
}
}
await getFd('01.mp3');
// 1. Create an AudioRecorder instance.
let audioRecorder = media.createAudioRecorder(); let audioRecorder = media.createAudioRecorder();
// 2. Set the callbacks. // 2.设置回调
SetCallBack(audioRecorder); SetCallBack(audioRecorder);
// 3. Set the recording parameters. // 3.设置录制参数
let audioRecorderConfig = { let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC , audioEncoder : media.AudioEncoder.AAC_LC ,
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS, format : media.AudioOutputFormat.AAC_ADTS,
uri : testFdNumber, // testFdNumber is generated by getFd. uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', // 文件需先由调用者创建,并给予适当的权限
location : { latitude : 30, longitude : 130}, location : { latitude : 30, longitude : 130},
} }
audioRecorder.prepare(audioRecorderConfig); audioRecorder.prepare(audioRecorderConfig);
// 4. Start recording. // 4.开始录制
audioRecorder.start(); // The start method can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete. audioRecorder.start(); // 需等待'prepare'事件回调完成后,才可调用start进行录制,触发'start'事件回调
// 5. Pause recording. // 5.暂停录制
audioRecorder.pause(); // The pause method can be called to trigger the 'pause' event callback only after the 'start' event callback is complete. audioRecorder.pause(); // 需等待'start'事件回调完成后,才可调用pause进行暂停,触发'pause'事件回调
// 6. Resume recording. // 6.恢复录制
audioRecorder.resume(); // The resume method can be called to trigger the 'resume' event callback only after the 'pause' event callback is complete. audioRecorder.resume(); // 需等待'pause'事件回调完成后,才可调用resume进行录制,触发'resume'事件回调
// 7. Stop recording. // 7.停止录制
audioRecorder.stop(); // The stop method can be called to trigger the 'stop' event callback only after the 'start' or 'resume' event callback is complete. audioRecorder.stop(); // 需等待'start'或'resume'事件回调完成后,才可调用stop进行暂停,触发'stop'事件回调
// 8. Reset recording. // 8.重置录制
audioRecorder.reset(); // The prepare method can be called for another recording only after the 'reset' event callback is complete. audioRecorder.reset(); // 触发'reset'事件回调后,重新进行prepare,才可重新录制
// 9. Release resources. // 9.释放资源
audioRecorder.release(); // The AudioRecorder resource is destroyed. audioRecorder.release(); // audioRecorder资源被销毁
audioRecorder = undefined; audioRecorder = undefined;
``` ```
### Normal Recording Scenario ### 正常录制场景
Unlike the full-process scenario, the normal recording scenario does not include the process of pausing and resuming recording. 与全流程场景不同,不包括暂停录制,恢复录制的过程。
```js ```js
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
function SetCallBack(audioPlayer) { function SetCallBack(audioPlayer) {
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. audioRecorder.on('prepare', () => { // 设置'prepare'事件回调
console.log('prepare success'); console.log('prepare success');
// The recording page is ready. You can click the Record button to start recording. // 录制界面可切换至已准备好,可点击录制按钮进行录制
}); });
audioRecorder.on('start', () => { // Set the 'start' event callback. audioRecorder.on('start', () => { // 设置'start'事件回调
console.log('audio recorder start success'); console.log('audio recorder start success');
// The Record button is changed to the pausable state. // 将录制按钮切换至可暂停状态
}); });
audioRecorder.on('stop', () => { // Set the 'stop' event callback. audioRecorder.on('stop', () => { // 设置'stop'事件回调
console.log('audio recorder stop success'); console.log('audio recorder stop success');
}); });
audioRecorder.on('release', () => { // Set the 'release' event callback. audioRecorder.on('release', () => { // 设置'release'事件回调
console.log('audio recorder release success'); console.log('audio recorder release success');
}); });
} }
// 1.创建实例
// pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Movies/01.mp3.
// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA.
async function getFd(pathName) {
let displayName = pathName;
const mediaTest = mediaLibrary.getMediaLibrary();
let fileKeyObj = mediaLibrary.FileKey;
let mediaType = mediaLibrary.MediaType.VIDEO;
let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO);
let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath);
if (dataUri != undefined) {
let args = dataUri.id.toString();
let fetchOp = {
selections : fileKeyObj.ID + "=?",
selectionArgs : [args],
}
let fetchFileResult = await mediaTest.getFileAssets(fetchOp);
let fileAsset = await fetchFileResult.getAllObject();
let fdNumber = await fileAsset[0].open('Rw');
fdNumber = "fd://" + fdNumber.toString();
testFdNumber = fdNumber;
}
}
await getFd('01.mp3');
// 1. Create an AudioRecorder instance.
let audioRecorder = media.createAudioRecorder(); let audioRecorder = media.createAudioRecorder();
// 2. Set the callbacks. // 2.设置回调
SetCallBack(audioRecorder); SetCallBack(audioRecorder);
// 3. Set the recording parameters. // 3.设置录制参数
let audioRecorderConfig = { let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC , audioEncoder : media.AudioEncoder.AAC_LC ,
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS, format : media.AudioOutputFormat.AAC_ADTS,
uri : testFdNumber, // testFdNumber is generated by getFd. uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', // 文件需先由调用者创建,并给予适当的权限
location : { latitude : 30, longitude : 130}, location : { latitude : 30, longitude : 130},
} }
audioRecorder.prepare(audioRecorderConfig) audioRecorder.prepare(audioRecorderConfig)
// 4. Start recording. // 4.开始录制
audioRecorder.start(); // The start method can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete. audioRecorder.start(); // 需等待'prepare'事件回调完成后,才可调用start进行录制,触发'start'事件回调
// 5. Stop recording. // 5.停止录制
audioRecorder.stop(); // The stop method can be called to trigger the 'stop' event callback only after the 'start' or 'resume' event callback is complete. audioRecorder.stop(); // 需等待'start'或'resume'事件回调完成后,才可调用stop进行暂停,触发'stop'事件回调
// 6. Release resources. // 6.释放资源
audioRecorder.release(); // The AudioRecorder resource is destroyed. audioRecorder.release(); // audioRecorder资源被销毁
audioRecorder = undefined; audioRecorder = undefined;
``` ```
# Video Playback Development # 视频播放开发指导
## When to Use ## 场景介绍
You can use video playback APIs to convert video data into visible signals, play the signals using output devices, and manage playback tasks. This document describes the following video playback development scenarios: full-process, normal playback, video switching, and loop playback. 视频播放的主要工作是将视频数据转码并输出到设备进行播放,同时管理播放任务。本文将对视频播放全流程、视频切换、视频循环播放等场景开发进行介绍说明。
**Figure 1** Video playback state transition **图1** 视频播放状态机
![en-us_image_video_state_machine](figures/en-us_image_video_state_machine.png) ![zh-ch_image_video_state_machine](figures/zh-ch_image_video_state_machine.png)
**Figure 2** Layer 0 diagram of video playback **图2** 视频播放零层图
![en-us_image_video_player](figures/en-us_image_video_player.png) ![zh-ch_image_video_player](figures/zh-ch_image_video_player.png)
Note: Video playback requires hardware capabilities such as display, audio, and codec. *注意:视频播放需要显示、音频、编解码等硬件能力。
1. A third-party application obtains a surface ID from the Xcomponent. 1. 三方应用从Xcomponent组件获取surfaceID。
2. The third-party application transfers the surface ID to the VideoPlayer JS. 2. 三方应用把surfaceID传递给VideoPlayer JS。
3. The media service flushes the frame data to the surface buffer. 3. 媒体服务把帧数据flush给surface buffer。
## How to Develop ## 开发步骤
For details about the APIs used for video playback, see [js-apis-media.md](../reference/apis/js-apis-media.md). 详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md)
### Full-Process Scenario ### 全流程场景
The full video playback process includes creating an instance, setting the URL, setting the surface ID, preparing for video playback, playing video, pausing playback, obtaining track information, seeking to a playback position, setting the volume, setting the playback speed, stopping playback, resetting the playback configuration, and releasing resources. 包含流程:创建实例,设置url,设置SurfaceId,准备播放视频,播放视频,暂停播放,获取轨道信息,跳转播放位置,设置音量,设置倍速,结束播放,重置,释放资源等流程。
For details about the **url** media source input types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_attributes). VideoPlayer支持的url媒体源输入类型可参考:[url属性说明](../reference/apis/js-apis-media.md#videoplayer_属性)
For details about how to create an Xcomponent, see [Xcomponent Creation](#Xcomponent).
```js ```js
import media from '@ohos.multimedia.media' let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象
import fileIO from '@ohos.fileio' let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID
let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method.
let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface.
// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded.
LoadXcomponent() {
surfaceID = this.$element('Xcomponent').getXComponentSurfaceId();
console.info('LoadXcomponent surfaceID is' + surfaceID);
}
// Report an error in the case of a function invocation failure. // 函数调用发生错误时用于上报错误信息
function failureCallback(error) { function failureCallback(error) {
console.info(`error happened,error Name is ${error.name}`); console.info(`error happened,error Name is ${error.name}`);
console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Code is ${error.code}`);
console.info(`error happened,error Message is ${error.message}`); console.info(`error happened,error Message is ${error.message}`);
} }
// Report an error in the case of a function invocation exception. // 当函数调用发生异常时用于上报错误信息
function catchCallback(error) { function catchCallback(error) {
console.info(`catch error happened,error Name is ${error.name}`); console.info(`catch error happened,error Name is ${error.name}`);
console.info(`catch error happened,error Code is ${error.code}`); console.info(`catch error happened,error Code is ${error.code}`);
console.info(`catch error happened,error Message is ${error.message}`); console.info(`catch error happened,error Message is ${error.message}`);
} }
// Used to print the video track information. // 用于打印视频轨道信息
function printfDescription(obj) { function printfDescription(obj) {
for (let item in obj) { for (let item in obj) {
let property = obj[item]; let property = obj[item];
...@@ -68,7 +57,7 @@ function printfDescription(obj) { ...@@ -68,7 +57,7 @@ function printfDescription(obj) {
} }
} }
// Call createVideoPlayer to create a VideoPlayer instance. // 调用createVideoPlayer接口返回videoPlayer实例对象
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
console.info('createVideoPlayer success!'); console.info('createVideoPlayer success!');
...@@ -78,41 +67,32 @@ await media.createVideoPlayer().then((video) => { ...@@ -78,41 +67,32 @@ await media.createVideoPlayer().then((video) => {
} }
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Set the FD (local playback) of the video file selected by the user. // 用户选择视频设置url
let fdPath = 'fd://' videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4';
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4';
await fileIO.open(path).then(fdNumber) => { // 该处需要调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中
fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath); // 设置surfaceID用于显示视频画面
}, (err) => {
console.info('open fd failed err is' + err);
}),catch((err) => {
console.info('open fd failed err is' + err);
});
videoPlayer.url = fdPath;
// Set the surface ID to display the video image.
await videoPlayer.setDisplaySurface(surfaceID).then(() => { await videoPlayer.setDisplaySurface(surfaceID).then(() => {
console.info('setDisplaySurface success'); console.info('setDisplaySurface success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Call the prepare interface to prepare for playback. // 调用prepare完成播放前准备工作
await videoPlayer.prepare().then(() => { await videoPlayer.prepare().then(() => {
console.info('prepare success'); console.info('prepare success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Call the play interface to start playback. // 调用play接口正式开始播放
await videoPlayer.play().then(() => { await videoPlayer.play().then(() => {
console.info('play success'); console.info('play success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Pause playback. // 暂停播放
await videoPlayer.pause().then(() => { await videoPlayer.pause().then(() => {
console.info('pause success'); console.info('pause success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Use a promise to obtain the video track information. // 通过promise回调方式获取视频轨道信息
let arrayDescription; let arrayDescription;
await videoPlayer.getTrackDescription().then((arrlist) => { await videoPlayer.getTrackDescription().then((arrlist) => {
if (typeof (arrlist) != 'undefined') { if (typeof (arrlist) != 'undefined') {
...@@ -126,74 +106,65 @@ for (let i = 0; i < arrayDescription.length; i++) { ...@@ -126,74 +106,65 @@ for (let i = 0; i < arrayDescription.length; i++) {
printfDescription(arrayDescription[i]); printfDescription(arrayDescription[i]);
} }
// Seek to the 50s position. For details about the input parameters, see the interface document. // 跳转播放时间到50s位置,具体入参意义请参考接口文档
let seekTime = 50000; let seekTime = 50000;
await videoPlayer.seek(seekTime, media.SeekMode._NEXT_SYNC).then((seekDoneTime) => { await videoPlayer.seek(seekTime, media.SeekMode._NEXT_SYNC).then((seekDoneTime) => {
console.info('seek success'); console.info('seek success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Set the volume. For details about the input parameters, see the interface document. // 音量设置接口,具体入参意义请参考接口文档
let volume = 0.5; let volume = 0.5;
await videoPlayer.setVolume(volume).then(() => { await videoPlayer.setVolume(volume).then(() => {
console.info('setVolume success'); console.info('setVolume success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Set the playback speed. For details about the input parameters, see the interface document. // 倍速设置接口,具体入参意义请参考接口文档
let speed = media.PlaybackRateMode.SPEED_FORWARD_2_00_X; let speed = media.PlaybackRateMode.SPEED_FORWARD_2_00_X;
await videoPlayer.setSpeed(speed).then(() => { await videoPlayer.setSpeed(speed).then(() => {
console.info('setSpeed success'); console.info('setSpeed success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Stop playback. // 结束播放
await videoPlayer.stop().then(() => { await videoPlayer.stop().then(() => {
console.info('stop success'); console.info('stop success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Reset the playback configuration. // 重置播放配置
await videoPlayer.reset().then(() => { await videoPlayer.reset().then(() => {
console.info('reset success'); console.info('reset success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Release playback resources. // 释放播放资源
await videoPlayer.release().then(() => { await videoPlayer.release().then(() => {
console.info('release success'); console.info('release success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Set the related instances to undefined. // 相关对象置undefined
videoPlayer = undefined; videoPlayer = undefined;
surfaceID = undefined; surfaceID = undefined;
``` ```
### Normal Playback Scenario ### 正常播放场景
```js ```js
import media from '@ohos.multimedia.media' let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象
import fileIO from '@ohos.fileio' let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID
let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method.
let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface.
// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded. // 函数调用发生错误时用于上报错误信息
LoadXcomponent() {
surfaceID = this.$element('Xcomponent').getXComponentSurfaceId();
console.info('LoadXcomponent surfaceID is' + surfaceID);
}
// Report an error in the case of a function invocation failure.
function failureCallback(error) { function failureCallback(error) {
console.info(`error happened,error Name is ${error.name}`); console.info(`error happened,error Name is ${error.name}`);
console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Code is ${error.code}`);
console.info(`error happened,error Message is ${error.message}`); console.info(`error happened,error Message is ${error.message}`);
} }
// Report an error in the case of a function invocation exception. // 当函数调用发生异常时用于上报错误信息
function catchCallback(error) { function catchCallback(error) {
console.info(`catch error happened,error Name is ${error.name}`); console.info(`catch error happened,error Name is ${error.name}`);
console.info(`catch error happened,error Code is ${error.code}`); console.info(`catch error happened,error Code is ${error.code}`);
console.info(`catch error happened,error Message is ${error.message}`); console.info(`catch error happened,error Message is ${error.message}`);
} }
// Set the 'playbackCompleted' event callback, which is triggered when the playback is complete. // 设置'playbackCompleted'事件回调,播放完成触发
function SetCallBack(videoPlayer) { function SetCallBack(videoPlayer) {
videoPlayer.on('playbackCompleted', () => { videoPlayer.on('playbackCompleted', () => {
console.info('video play finish'); console.info('video play finish');
...@@ -207,7 +178,7 @@ function SetCallBack(videoPlayer) { ...@@ -207,7 +178,7 @@ function SetCallBack(videoPlayer) {
}); });
} }
// Call createVideoPlayer to create a VideoPlayer instance. // 调用createVideoPlayer接口返回videoPlayer实例对象
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
console.info('createVideoPlayer success!'); console.info('createVideoPlayer success!');
...@@ -217,69 +188,51 @@ await media.createVideoPlayer().then((video) => { ...@@ -217,69 +188,51 @@ await media.createVideoPlayer().then((video) => {
} }
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Set the event callbacks. // 设置事件回调
SetCallBack(videoPlayer); SetCallBack(videoPlayer);
// Set the FD (local playback) of the video file selected by the user. // 用户选择视频设置url
let fdPath = 'fd://' videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4';
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4';
await fileIO.open(path).then(fdNumber) => { // 该处需要调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中
fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath); // 设置surfaceID用于显示视频画面
}, (err) => {
console.info('open fd failed err is' + err);
}),catch((err) => {
console.info('open fd failed err is' + err);
});
videoPlayer.url = fdPath;
// Set the surface ID to display the video image.
await videoPlayer.setDisplaySurface(surfaceID).then(() => { await videoPlayer.setDisplaySurface(surfaceID).then(() => {
console.info('setDisplaySurface success'); console.info('setDisplaySurface success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Call the prepare interface to prepare for playback. // 调用prepare完成播放前准备工作
await videoPlayer.prepare().then(() => { await videoPlayer.prepare().then(() => {
console.info('prepare success'); console.info('prepare success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Call the play interface to start playback. // 调用play接口正式开始播放
await videoPlayer.play().then(() => { await videoPlayer.play().then(() => {
console.info('play success'); console.info('play success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
``` ```
### Switching to the Next Video Clip ### 切视频场景
```js ```js
import media from '@ohos.multimedia.media' let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象
import fileIO from '@ohos.fileio' let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID
let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method.
let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface.
// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded.
LoadXcomponent() {
surfaceID = this.$element('Xcomponent').getXComponentSurfaceId();
console.info('LoadXcomponent surfaceID is' + surfaceID);
}
// Report an error in the case of a function invocation failure. // 函数调用发生错误时用于上报错误信息
function failureCallback(error) { function failureCallback(error) {
console.info(`error happened,error Name is ${error.name}`); console.info(`error happened,error Name is ${error.name}`);
console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Code is ${error.code}`);
console.info(`error happened,error Message is ${error.message}`); console.info(`error happened,error Message is ${error.message}`);
} }
// Report an error in the case of a function invocation exception. // 当函数调用发生异常时用于上报错误信息
function catchCallback(error) { function catchCallback(error) {
console.info(`catch error happened,error Name is ${error.name}`); console.info(`catch error happened,error Name is ${error.name}`);
console.info(`catch error happened,error Code is ${error.code}`); console.info(`catch error happened,error Code is ${error.code}`);
console.info(`catch error happened,error Message is ${error.message}`); console.info(`catch error happened,error Message is ${error.message}`);
} }
// Set the 'playbackCompleted' event callback, which is triggered when the playback is complete. // 设置'playbackCompleted'事件回调,播放完成触发
function SetCallBack(videoPlayer) { function SetCallBack(videoPlayer) {
videoPlayer.on('playbackCompleted', () => { videoPlayer.on('playbackCompleted', () => {
console.info('video play finish'); console.info('video play finish');
...@@ -293,7 +246,7 @@ function SetCallBack(videoPlayer) { ...@@ -293,7 +246,7 @@ function SetCallBack(videoPlayer) {
}); });
} }
// Call createVideoPlayer to create a VideoPlayer instance. // 调用createVideoPlayer接口返回videoPlayer实例对象
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
console.info('createVideoPlayer success!'); console.info('createVideoPlayer success!');
...@@ -303,104 +256,74 @@ await media.createVideoPlayer().then((video) => { ...@@ -303,104 +256,74 @@ await media.createVideoPlayer().then((video) => {
} }
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Set the event callbacks. // 设置事件回调
SetCallBack(videoPlayer); SetCallBack(videoPlayer);
// Set the FD (local playback) of the video file selected by the user. // 用户选择视频设置url
let fdPath = 'fd://' videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4';
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4';
await fileIO.open(path).then(fdNumber) => { // 该处需要调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中
fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath); // 设置surfaceID用于显示视频画面
}, (err) => {
console.info('open fd failed err is' + err);
}),catch((err) => {
console.info('open fd failed err is' + err);
});
videoPlayer.url = fdPath;
// Set the surface ID to display the video image.
await videoPlayer.setDisplaySurface(surfaceID).then(() => { await videoPlayer.setDisplaySurface(surfaceID).then(() => {
console.info('setDisplaySurface success'); console.info('setDisplaySurface success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Call the prepare interface to prepare for playback. // 调用prepare完成播放前准备工作
await videoPlayer.prepare().then(() => { await videoPlayer.prepare().then(() => {
console.info('prepare success'); console.info('prepare success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Call the play interface to start playback. // 调用play接口正式开始播放
await videoPlayer.play().then(() => { await videoPlayer.play().then(() => {
console.info('play success'); console.info('play success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Send the instruction to switch to the next video clip after a period of time. // 播放一段时间后,下发切视频指令
// Reset the playback configuration. // 重置播放配置
await videoPlayer.reset().then(() => { await videoPlayer.reset().then(() => {
console.info('reset success'); console.info('reset success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Set the FD (local playback) of the video file selected by the user. videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/next.mp4';
let fdNextPath = 'fd://'
let nextPath = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/02.mp4'; // 设置surfaceID用于显示视频画面
await fileIO.open(nextPath).then(fdNumber) => {
fdNextPath = fdNextPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdNextPath);
}, (err) => {
console.info('open fd failed err is' + err);
}),catch((err) => {
console.info('open fd failed err is' + err);
});
videoPlayer.url = fdNextPath;
// Set the surface ID to display the video image.
await videoPlayer.setDisplaySurface(surfaceID).then(() => { await videoPlayer.setDisplaySurface(surfaceID).then(() => {
console.info('setDisplaySurface success'); console.info('setDisplaySurface success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Call the prepare interface to prepare for playback. // 调用prepare完成播放前准备工作
await videoPlayer.prepare().then(() => { await videoPlayer.prepare().then(() => {
console.info('prepare success'); console.info('prepare success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Call the play interface to start playback. // 调用play接口正式开始播放
await videoPlayer.play().then(() => { await videoPlayer.play().then(() => {
console.info('play success'); console.info('play success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
``` ```
### Looping a Video Clip ### 单个视频循环场景
```js ```js
import media from '@ohos.multimedia.media' let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象
import fileIO from '@ohos.fileio' let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID
let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method.
let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface.
// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded. // 函数调用发生错误时用于上报错误信息
LoadXcomponent() {
surfaceID = this.$element('Xcomponent').getXComponentSurfaceId();
console.info('LoadXcomponent surfaceID is' + surfaceID);
}
// Report an error in the case of a function invocation failure.
function failureCallback(error) { function failureCallback(error) {
console.info(`error happened,error Name is ${error.name}`); console.info(`error happened,error Name is ${error.name}`);
console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Code is ${error.code}`);
console.info(`error happened,error Message is ${error.message}`); console.info(`error happened,error Message is ${error.message}`);
} }
// Report an error in the case of a function invocation exception. // 当函数调用发生异常时用于上报错误信息
function catchCallback(error) { function catchCallback(error) {
console.info(`catch error happened,error Name is ${error.name}`); console.info(`catch error happened,error Name is ${error.name}`);
console.info(`catch error happened,error Code is ${error.code}`); console.info(`catch error happened,error Code is ${error.code}`);
console.info(`catch error happened,error Message is ${error.message}`); console.info(`catch error happened,error Message is ${error.message}`);
} }
// Set the 'playbackCompleted' event callback, which is triggered when the playback is complete. // 设置'playbackCompleted'事件回调,播放完成触发
function SetCallBack(videoPlayer) { function SetCallBack(videoPlayer) {
videoPlayer.on('playbackCompleted', () => { videoPlayer.on('playbackCompleted', () => {
console.info('video play finish'); console.info('video play finish');
...@@ -414,7 +337,7 @@ function SetCallBack(videoPlayer) { ...@@ -414,7 +337,7 @@ function SetCallBack(videoPlayer) {
}); });
} }
// Call createVideoPlayer to create a VideoPlayer instance. // 调用createVideoPlayer接口返回videoPlayer实例对象
await media.createVideoPlayer().then((video) => { await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') { if (typeof (video) != 'undefined') {
console.info('createVideoPlayer success!'); console.info('createVideoPlayer success!');
...@@ -424,50 +347,29 @@ await media.createVideoPlayer().then((video) => { ...@@ -424,50 +347,29 @@ await media.createVideoPlayer().then((video) => {
} }
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Set the event callbacks. // 设置事件回调
SetCallBack(videoPlayer); SetCallBack(videoPlayer);
// Set the FD (local playback) of the video file selected by the user. // 用户选择视频设置url
let fdPath = 'fd://' videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4';
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4';
await fileIO.open(path).then(fdNumber) => { // 该处需要调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中
fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath); // 设置surfaceID用于显示视频画面
}, (err) => {
console.info('open fd failed err is' + err);
}),catch((err) => {
console.info('open fd failed err is' + err);
});
videoPlayer.url = fdPath;
// Set the surface ID to display the video image.
await videoPlayer.setDisplaySurface(surfaceID).then(() => { await videoPlayer.setDisplaySurface(surfaceID).then(() => {
console.info('setDisplaySurface success'); console.info('setDisplaySurface success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Call the prepare interface to prepare for playback. // 调用prepare完成播放前准备工作
await videoPlayer.prepare().then(() => { await videoPlayer.prepare().then(() => {
console.info('prepare success'); console.info('prepare success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Set the loop playback attribute. // 设置循环播放属性
videoPlayer.loop = true; videoPlayer.loop = true;
// Call the play interface to start playback. // 调用play接口正式开始播放
await videoPlayer.play().then(() => { await videoPlayer.play().then(() => {
console.info('play success'); console.info('play success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
``` ```
\ No newline at end of file
### Xcomponent Creation
```js
The Xcomponent is used to obtain the surface ID during video playback. You need to create an xxx.hml file and add the following code to the xxx.hml file, where xxx is the same as that in the xxx.js file:
<xcomponent id = 'Xcomponent'
if = "{{isFlush}}" // Refresh the surface ID. To enable automatic loading of the Xcomponent and obtain the new surface ID, assign **false** to **isFlush** and then assign **true** to **isFlush**.
type = 'surface'
onload = 'LoadXcomponent' // Default interface for loading the Xcomponent.
style = "width:720px;height:480px;border-color:red;border-width:5px;"> // Set the window width, height, and other attributes.
</xcomponent>
```
# Video Recording Development # 视频录制开发指导
## When to Use ## 场景介绍
During video recording, audio and video signals are captured, encoded, and saved to files. You can specify parameters such as the encoding format, encapsulation format, and file path for video recording. 视频录制的主要工作是捕获音视频信号,完成音视频编码并保存到文件中,帮助开发者轻松实现音视频录制功能。它允许调用者指定录制的编码格式、封装格式、文件路径等参数。
**Figure 1** Video recording state transition **图1** 视频录制状态机
![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png) ![zh-ch_image_video_recorder_state_machine](figures/zh-ch_image_video_recorder_state_machine.png)
**Figure 2** Layer 0 diagram of video recording **图2** 视频录制零层图
![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png) ![zh-ch_image_video_recorder_zero](figures/zh-ch_image_video_recorder_zero.png)
## How to Develop ## 开发步骤
For details about the APIs used for video recording, see [js-apis-media.md](../reference/apis/js-apis-media.md). 详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md)
### Full-Process Scenario ### 全流程场景
The full video recording process includes creating an instance, setting recording parameters, recording video, pausing, resuming, and stopping recording, and releasing resources. 包含流程:创建实例,设置录制参数,录制视频,暂停录制,恢复录制,停止录制,释放资源等流程。
```js ```js
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
// pathName indicates the passed recording file name, for example, 01.mp4. The generated file address is /storage/media/100/local/files/Movies/01.mp4.
// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA.
async function getFd(pathName) {
let displayName = pathName;
const mediaTest = mediaLibrary.getMediaLibrary();
let fileKeyObj = mediaLibrary.FileKey;
let mediaType = mediaLibrary.MediaType.VIDEO;
let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO);
let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath);
if (dataUri != undefined) {
let args = dataUri.id.toString();
let fetchOp = {
selections : fileKeyObj.ID + "=?",
selectionArgs : [args],
}
let fetchFileResult = await mediaTest.getFileAssets(fetchOp);
let fileAsset = await fetchFileResult.getAllObject();
let fdNumber = await fileAsset[0].open('Rw');
fdNumber = "fd://" + fdNumber.toString();
testFdNumber = fdNumber;
}
}
await getFd('01.mp4');
let videoProfile = { let videoProfile = {
audioBitrate : 48000, audioBitrate : 48000,
audioChannels : 2, audioChannels : 2,
...@@ -70,29 +40,28 @@ let videoConfig = { ...@@ -70,29 +40,28 @@ let videoConfig = {
audioSourceType : 1, audioSourceType : 1,
videoSourceType : 0, videoSourceType : 0,
profile : videoProfile, profile : videoProfile,
url: testFdNumber, // testFdNumber is generated by getFd. url : 'file:///data/media/01.mp4',
orientationHint : 0, orientationHint : 0,
location : { latitude : 30, longitude : 130 }, location : { latitude : 30, longitude : 130 },
} }
// Error callback triggered in the case of an error // 当发生错误上上报的错误回调接口
function failureCallback(error) { function failureCallback(error) {
console.info('error happened, error name is ' + error.name); console.info('error happened, error name is ' + error.name);
console.info('error happened, error code is ' + error.code); console.info('error happened, error code is ' + error.code);
console.info('error happened, error message is ' + error.message); console.info('error happened, error message is ' + error.message);
} }
// Error callback triggered in the case of an exception // 当发生异常时,系统调用的错误回调接口
function catchCallback(error) { function catchCallback(error) {
console.info('catch error happened, error name is ' + error.name); console.info('catch error happened, error name is ' + error.name);
console.info('catch error happened, error code is ' + error.code); console.info('catch error happened, error code is ' + error.code);
console.info('catch error happened, error message is ' + error.message); console.info('catch error happened, error message is ' + error.message);
} }
let videoRecorder = null; // videoRecorder is an empty object and assigned with a value after createVideoRecorder is successfully called. let videoRecorder = null; // videoRecorder空对象在createVideoRecorder成功后赋值
let surfaceID = null; // Used to save the surface ID returned by getInputSurface. let surfaceID = null; // 用于保存getInputSurface返回的surfaceID
// 创建videoRecorder对象
// Create a VideoRecorder object.
await media.createVideoRecorder().then((recorder) => { await media.createVideoRecorder().then((recorder) => {
console.info('case createVideoRecorder called'); console.info('case createVideoRecorder called');
if (typeof (recorder) != 'undefined') { if (typeof (recorder) != 'undefined') {
...@@ -103,45 +72,46 @@ await media.createVideoRecorder().then((recorder) => { ...@@ -103,45 +72,46 @@ await media.createVideoRecorder().then((recorder) => {
} }
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Obtain the surface ID, save it, and pass it to camera-related interfaces. // 获取surfaceID并保存下来传递给camera相关接口
await videoRecorder.getInputSurface().then((surface) => { await videoRecorder.getInputSurface().then((surface) => {
console.info('getInputSurface success'); console.info('getInputSurface success');
surfaceID = surface; surfaceID = surface;
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Video recording depends on camera-related interfaces. The following operations can be performed only after the video output start interface is invoked. // 视频录制依赖相机相关接口,以下需要先调用相机起流接口后才能继续执行
// Start video recording. // 视频录制启动接口
await videoRecorder.start().then(() => { await videoRecorder.start().then(() => {
console.info('start success'); console.info('start success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Pause video playback before the video output stop interface is invoked. // 调用pause接口时需要暂停camera出流
await videoRecorder.pause().then(() => { await videoRecorder.pause().then(() => {
console.info('pause success'); console.info('pause success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Resume video playback after the video output start interface is invoked. // 调用resume接口时需要恢复camera出流
await videoRecorder.resume().then(() => { await videoRecorder.resume().then(() => {
console.info('resume success'); console.info('resume success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Stop video recording after the video output stop interface is invoked. // 停止camera出流后,停止视频录制
await videoRecorder.stop().then(() => { await videoRecorder.stop().then(() => {
console.info('stop success'); console.info('stop success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Reset the recording configuration. // 重置录制相关配置
await videoRecorder.reset().then(() => { await videoRecorder.reset().then(() => {
console.info('reset success'); console.info('reset success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Release the video recording resources and camera object resources. // 释放视频录制相关资源并释放camera对象相关资源
await videoRecorder.release().then(() => { await videoRecorder.release().then(() => {
console.info('release success'); console.info('release success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
// Set the related object to null. // 相关对象置null
videoRecorder = null; videoRecorder = null;
surfaceID = null; surfaceID = null;
``` ```
# 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 various media services covering audio and video, which provide the following capabilities: - 音频播放([AudioPlayer](#audioplayer)
- 视频播放([VideoPlayer](#videoplayer8)
- 音频录制([AudioRecorder](#audiorecorder)
- 视频录制([VideoRecorder](#VideoRecorder<sup>8+</sup>))
- Audio playback ([AudioPlayer](#audioplayer)) 后续将提供以下功能:DataSource音视频播放、音视频编解码、容器封装解封装、媒体能力查询等功能。
- Video playback ([VideoPlayer](#videoplayer8))
- Audio recording ([AudioRecorder](#audiorecorder))
- Video recording ([VideoRecorder](#VideoRecorder<sup>8+</sup>))
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
```js ```js
import media from '@ohos.multimedia.media'; import media from '@ohos.multimedia.media';
...@@ -24,41 +21,94 @@ import media from '@ohos.multimedia.media'; ...@@ -24,41 +21,94 @@ import media from '@ohos.multimedia.media';
createAudioPlayer(): [AudioPlayer](#audioplayer) createAudioPlayer(): [AudioPlayer](#audioplayer)
Creates an **AudioPlayer** instance in synchronous mode. 同步方式创建音频播放实例。
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| --------------------------- | ------------------------------------------------------------ | | --------------------------- | ------------------------------------------------------------ |
| [AudioPlayer](#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.| | [AudioPlayer](#audioplayer) | 返回AudioPlayer类实例,失败时返回null。可用于音频播放、暂停、停止等操作。 |
**Example** **示例:**
```js ```js
let audioPlayer = media.createAudioPlayer(); var audioPlayer = media.createAudioPlayer();
```
## media.createAudioPlayerAsync<sup>8+</sup>
createAudioPlayerAsync(callback: AsyncCallback\<[AudioPlayer](#audioplayer)>): void
异步方式创建音频播放实例。通过注册回调函数获取返回值。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------ | ---- | ------------------------------ |
| callback | AsyncCallback<[AudioPlayer](#audioplayer)> | 是 | 异步创建音频播放实例回调方法。 |
**示例:**
```js
media.createAudioPlayerAsync((error, audio) => {
if (typeof(audio) != 'undefined') {
audioPlayer = audio;
console.info('audio createAudioPlayerAsync success');
} else {
console.info(`audio createAudioPlayerAsync fail, error:${error.message}`);
}
});
```
## media.createAudioPlayerAsync<sup>8+</sup>
createAudioPlayerAsync: Promise<[AudioPlayer](#audioplayer)>
异步方式创建音频播放实例。通过Promise获取返回值。
**返回值:**
| 类型 | 说明 |
| ------------------------------------ | ----------------------------------- |
| Promise<[AudioPlayer](#audioplayer)> | 异步创建音频播放实例Promise返回值。 |
**示例:**
```js
function failureCallback(error) {
console.info(`audio failureCallback, error:${error.message}`);
}
function catchCallback(error) {
console.info(`audio catchCallback, error:${error.message}`);
}
await media.createAudioPlayerAsync.then((audio) => {
if (typeof(audio) != 'undefined') {
audioPlayer = audio;
console.info('audio createAudioPlayerAsync success');
} else {
console.info('audio createAudioPlayerAsync fail');
}
}, failureCallback).catch(catchCallback);
``` ```
## media.createVideoPlayer<sup>8+</sup> ## media.createVideoPlayer<sup>8+</sup>
createVideoPlayer(callback: AsyncCallback\<[VideoPlayer](#videoplayer8)>): void createVideoPlayer(callback: AsyncCallback\<[VideoPlayer](#videoplayer8)>): 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](#videoplayer8)> | Yes | Callback used to return the **VideoPlayer** instance created.| | callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | 是 | 异步创建视频播放实例回调方法。 |
**Example** **示例:**
```js ```js
let videoPlayer
media.createVideoPlayer((error, video) => { media.createVideoPlayer((error, video) => {
if (typeof(video) != 'undefined') { if (typeof(video) != 'undefined') {
videoPlayer = video; videoPlayer = video;
...@@ -73,21 +123,17 @@ media.createVideoPlayer((error, video) => { ...@@ -73,21 +123,17 @@ media.createVideoPlayer((error, video) => {
createVideoPlayer: Promise<[VideoPlayer](#videoplayer8)> createVideoPlayer: Promise<[VideoPlayer](#videoplayer8)>
Creates a **VideoPlayer** instance in asynchronous mode. This API uses a promise to return the result. 异步方式创建视频播放实例,通过Promise获取返回值。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer **返回值:**
**Return value** | 类型 | 说明 |
| Type | Description |
| ------------------------------------- | ----------------------------------- | | ------------------------------------- | ----------------------------------- |
| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the **VideoPlayer** instance created.| | Promise<[VideoPlayer](#videoplayer8)> | 异步创建视频播放实例Promise返回值。 |
**Example** **示例:**
```js ```js
let videoPlayer
function failureCallback(error) { function failureCallback(error) {
console.info(`video failureCallback, error:${error.message}`); console.info(`video failureCallback, error:${error.message}`);
} }
...@@ -109,70 +155,117 @@ await media.createVideoPlayer.then((video) => { ...@@ -109,70 +155,117 @@ await media.createVideoPlayer.then((video) => {
createAudioRecorder(): AudioRecorder createAudioRecorder(): AudioRecorder
Creates an **AudioRecorder** instance to control audio recording. 创建音频录制的实例来控制音频的录制。
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder **返回值:**
**Return value** | 类型 | 说明 |
| Type | Description |
| ------------------------------- | ----------------------------------------- | | ------------------------------- | ----------------------------------------- |
| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise.| | [AudioRecorder](#audiorecorder) | 返回AudioRecorder类实例,失败时返回null。 |
**Example** **示例:**
```js ```js
let audiorecorder = media.createAudioRecorder(); let audiorecorder = media.createAudioRecorder();
``` ```
## media.createVideoRecorder<sup>8+</sup> ## media.createAudioRecorderAsync<sup>8+</sup>
createAudioRecorderAsync(callback: AsyncCallback\<[AudioRecorder](#audiorecorder)>): void
异步方式创建音频录制实例。通过注册回调函数获取返回值。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[AudioRecorder](#audiorecorder)> | 是 | 异步创建音频录制实例回调方法。 |
createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder8)>): void **示例:**
Creates a **VideoRecorder** instance in asynchronous mode. This API uses a callback to return the result. ```js
media.createAudioRecorderAsync((error, audio) => {
if (typeof(audio) != 'undefined') {
audioRecorder = audio;
console.info('audio createAudioRecorderAsync success');
} else {
console.info(`audio createAudioRecorderAsync fail, error:${error.message}`);
}
});
```
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder ## media.createAudioRecorderAsync<sup>8+</sup>
**Parameters** createAudioRecorderAsync: Promise<[AudioRecorder](#audiorecorder)>
| Name | Type | Mandatory| Description | 异步方式创建音频录制实例。通过Promise获取返回值。
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoRecorder](#videorecorder8)> | Yes | Callback used to return the **VideoRecorder** instance created.|
**Example** **返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ----------------------------------- |
| Promise<[AudioRecorder](#audiorecorder)> | 异步创建音频录制实例Promise返回值。 |
**示例:**
```js ```js
let videoRecorder function failureCallback(error) {
console.info(`audio failureCallback, error:${error.message}`);
}
function catchCallback(error) {
console.info(`audio catchCallback, error:${error.message}`);
}
media.createVideoRecorder((error, video) => { await media.createAudioRecorderAsync.then((audio) => {
if (typeof(audio) != 'undefined') {
audioRecorder = audio;
console.info('audio createAudioRecorderAsync success');
} else {
console.info('audio createAudioRecorderAsync fail');
}
}, failureCallback).catch(catchCallback);
```
## media.createVideoRecorderAsync<sup>8+</sup>
createVideoRecorderAsync(callback: AsyncCallback\<[VideoRecorder](#videorecorder8)>): void
异步方式创建视频录制实例。通过注册回调函数获取返回值。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoRecorder](#videorecorder8)> | 是 | 异步创建视频录制实例回调方法。 |
**示例:**
```js
media.createVideoRecorderAsync((error, video) => {
if (typeof(video) != 'undefined') { if (typeof(video) != 'undefined') {
videoRecorder = video; videoRecorder = video;
console.info('video createVideoRecorder success'); console.info('video createVideoRecorderAsync success');
} else { } else {
console.info(`video createVideoRecorder fail, error:${error.message}`); console.info(`video createVideoRecorderAsync fail, error:${error.message}`);
} }
}); });
``` ```
## media.createVideoRecorder<sup>8+</sup> ## media.createVideoRecorderAsync<sup>8+</sup>
createVideoRecorder: Promise<[VideoRecorder](#videorecorder8)>
Creates a **VideoRecorder** instance in asynchronous mode. This API uses a promise to return the result. createVideoRecorderAsync: Promise<[VideoRecorder](#videorecorder8)>
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder 异步方式创建视频录制实例。通过Promise获取返回值。
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| ----------------------------------------- | ----------------------------------- | | ----------------------------------------------------- | ----------------------------------- |
| Promise<[VideoRecorder](#videorecorder8)> | Promise used to return the **VideoRecorder** instance created.| | Promise<[VideoRecorder](#videorecorder8)> | 异步创建视频录制实例Promise返回值。 |
**Example** **示例:**
```js ```js
let videoRecorder
function failureCallback(error) { function failureCallback(error) {
console.info(`video failureCallback, error:${error.message}`); console.info(`video failureCallback, error:${error.message}`);
} }
...@@ -180,12 +273,12 @@ function catchCallback(error) { ...@@ -180,12 +273,12 @@ function catchCallback(error) {
console.info(`video catchCallback, error:${error.message}`); console.info(`video catchCallback, error:${error.message}`);
} }
await media.createVideoRecorder.then((video) => { await media.createVideoRecorderAsync.then((video) => {
if (typeof(video) != 'undefined') { if (typeof(video) != 'undefined') {
videoRecorder = video; videoRecorder = video;
console.info('video createVideoRecorder success'); console.info('video createVideoRecorderAsync success');
} else { } else {
console.info('video createVideoRecorder fail'); console.info('video createVideoRecorderAsync fail');
} }
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
``` ```
...@@ -194,97 +287,97 @@ await media.createVideoRecorder.then((video) => { ...@@ -194,97 +287,97 @@ await media.createVideoRecorder.then((video) => {
## MediaErrorCode<sup>8+</sup> ## MediaErrorCode<sup>8+</sup>
Enumerates the media error codes. 媒体服务错误类型枚举
| Name | Value | Description | | 名称 | 值 | 说明 |
| -------------------------- | ---- | ------------------------------------------------------------ | | -------------------------- | ---- | -------------------------------------- |
| MSERR_OK | 0 | The operation is successful.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MSERR_OK | 0 | 表示操作成功。 |
| MSERR_NO_MEMORY | 1 | Failed to allocate memory. The system may have no available memory.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MSERR_NO_MEMORY | 1 | 表示申请内存失败,系统可能无可用内存。 |
| MSERR_OPERATION_NOT_PERMIT | 2 | No permission to perform this operation.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MSERR_OPERATION_NOT_PERMIT | 2 | 表示无权限执行此操作。 |
| MSERR_INVALID_VAL | 3 | Invalid input parameter.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MSERR_INVALID_VAL | 3 | 表示传入入参无效。 |
| MSERR_IO | 4 | An I/O error occurs.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MSERR_IO | 4 | 表示发生IO错误。 |
| MSERR_TIMEOUT | 5 | The operation times out.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MSERR_TIMEOUT | 5 | 表示操作超时。 |
| MSERR_UNKNOWN | 6 | An unknown error occurs.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MSERR_UNKNOWN | 6 | 表示未知错误。 |
| MSERR_SERVICE_DIED | 7 | Invalid server.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MSERR_SERVICE_DIED | 7 | 表示服务端失效。 |
| MSERR_INVALID_STATE | 8 | The operation is not allowed in the current state.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MSERR_INVALID_STATE | 8 | 表示在当前状态下,不允许执行此操作。 |
| MSERR_UNSUPPORTED | 9 | The operation is not supported in the current version.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MSERR_UNSUPPORTED | 9 | 表示在当前版本下,不支持此操作。 |
## MediaType<sup>8+</sup> ## MediaType<sup>8+</sup>
Enumerates the media types. 媒体类型枚举
| Name | Value | Description | | 名称 | 值 | 说明 |
| -------------- | ---- | ------------------------------------------------------------ | | ------------------- | ---- | ------------------ |
| MEDIA_TYPE_AUD | 0 | Media.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MEDIA_TYPE_AUD | 0 | 表示音频。 |
| MEDIA_TYPE_VID | 1 | Video.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MEDIA_TYPE_VID | 1 | 表示视频。 |
| MEDIA_TYPE_SUBTITLE | 2 | 表示字幕:开发中。 |
## CodecMimeType<sup>8+</sup> ## CodecMimeType<sup>8+</sup>
Enumerates the codec MIME types. Codec MIME类型枚举
| Name | Value | Description | | 名称 | 值 | 说明 |
| ------------ | ----------------- | ------------------------------------------------------------ | | ------------ | ----------------- | ------------------------ |
| VIDEO_MPEG4 | "video/mp4v-es" | Video in MPEG-4 format.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | VIDEO_MPEG4 | ”video/mp4v-es“ | 表示视频/mpeg4类型。 |
| AUDIO_AAC | "audio/mp4a-latm" | Audio in MP4A-LATM format.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | AUDIO_MPEG | "audio/mpeg" | 表示音频/mpeg类型。 |
| AUDIO_VORBIS | "audio/vorbis" | Audio in Vorbis format.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | AUDIO_AAC | "audio/mp4a-latm" | 表示音频/mp4a-latm类型。 |
| AUDIO_FLAC | "audio/flac" | Audio in FLAC format.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | AUDIO_VORBIS | "audio/vorbis" | 表示音频/vorbis类型。 |
| AUDIO_FLAC | "audio/flac" | 表示音频/flac类型。 |
## MediaDescriptionKey<sup>8+</sup> ## MediaDescriptionKey<sup>8+</sup>
Enumerates the media description keys. 媒体信息描述枚举
| Name | Value | Description | | 名称 | 值 | 说明 |
| ------------------------ | --------------- | ------------------------------------------------------------ | | ------------------------ | --------------- | ------------------------------------------------------------ |
| MD_KEY_TRACK_INDEX | "track_index" | Track index, which is a number.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MD_KEY_TRACK_INDEX | "track_index" | 表示轨道序号,其对应键值类型为number。 |
| MD_KEY_TRACK_TYPE | "track_type" | Track type, which is a number. For details, see [MediaType](#mediatype8).<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MD_KEY_TRACK_TYPE | "track_type" | 表示轨道类型,其对应键值类型为number,参考[MediaType](#mediatype8)|
| MD_KEY_CODEC_MIME | "codec_mime" | Codec MIME type, which is a string.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MD_KEY_CODEC_MIME | "codec_mime" | 表示codec_mime类型,其对应键值类型为string。 |
| MD_KEY_DURATION | "duration" | Media duration, which is a number, in units of ms.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MD_KEY_DURATION | "duration" | 表示媒体时长,其对应键值类型为number,单位为ms。 |
| MD_KEY_BITRATE | "bitrate" | Bit rate, which is a number, in units of bit/s.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MD_KEY_BITRATE | "bitrate" | 表示比特率,其对应键值类型为number,单位为bps。 |
| MD_KEY_WIDTH | "width" | Video width, which is a number, in units of pixel.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MD_KEY_WIDTH | "width" | 表示视频宽度,其对应键值类型为number,单位为像素。 |
| MD_KEY_HEIGHT | "height" | Video height, which is a number, in units of pixel.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MD_KEY_HEIGHT | "height" | 表示视频高度,其对应键值类型为number,单位为像素。 |
| MD_KEY_FRAME_RATE | "frame_rate" | Video frame rate, which is a number, in units of 100 fps.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MD_KEY_FRAME_RATE | "frame_rate" | 表示视频帧率,其对应键值类型为number,单位为100fps。 |
| MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | Number of audio channels, which is a number.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | 表示声道数,其对应键值类型为number。 |
| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | Sampling rate, which is a number, in units of Hz.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | 表示采样率,其对应键值类型为number,单位为HZ。 |
## BufferingInfoType<sup>8+</sup> ## BufferingInfoType<sup>8+</sup>
Enumerates the buffering event types. 缓存事件类型枚举
| Name | Value | Description | | 名称 | 值 | 说明 |
| ----------------- | ---- | ------------------------------------------------------------ | | ----------------- | ---- | -------------------------- |
| BUFFERING_START | 1 | Buffering starts.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | BUFFERING_START | 1 | 表示开始缓存。 |
| BUFFERING_END | 2 | Buffering ends.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | BUFFERING_END | 2 | 表示结束缓存。 |
| BUFFERING_PERCENT | 3 | Buffering progress, in percent.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | BUFFERING_PERCENT | 3 | 表示缓存百分比。 |
| CACHED_DURATION | 4 | Cache duration, in milliseconds.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | CACHED_DURATION | 4 | 表示缓存时长,单位为毫秒。 |
## AudioPlayer ## AudioPlayer
Provides methods to manage and play audio. Before calling a method of **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayer) to create an **AudioPlayer** instance. 音频播放管理类,用于管理和播放音频媒体。在调用AudioPlayer的方法前,需要先通过[createAudioPlayer()](#media.createaudioplayer)[createAudioPlayerAsync()](#media.createaudioplayerasync8)构建一个[AudioPlayer](#audioplayer)实例。
For details about the audio playback demo, see [Audio Playback Development](../../media/audio-playback.md). 音频播放demo可参考:[音频播放开发指导](../../media/audio-playback.md)
### Attributes<a name=audioplayer_attributes></a> ### 属性<a name=audioplayer_属性></a>
| Name | Type | Readable| Writable| Description | | 名称 | 类型 | 可读 | 可写 | 说明 |
| ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | | ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ |
| src | string | Yes | Yes | Audio media URI. The mainstream audio formats (MP4, AAC, MP3, and OGG) are supported.<br>**Example of supported URIs**:<br>1. FD playback: fd://xxx<br>![en-us_image_0000001164217678](figures/en-us_image_url.png)<br>2. HTTP network playback path (under development)<br>3. HLS network playback path (under development)<br>**Note**:<br>To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.<br>**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| | src | string | 是 | 是 | 音频媒体URI,支持当前主流的音频格式(mp4、aac、mp3、ogg)。<br>**支持路径示例**<br>1、本地绝对路径:file:///data/data/ohos.xxx.xxx/files/test.mp4<br>![zh-cn_image_0000001164217678](figures/zh-cn_image_0000001164217678.png)<br>2、http网络播放路径:开发中<br>3、hls网络播放路径:开发中<br>4、fd类型播放:开发中<br>**注意事项**<br>媒体素材需至少赋予读权限后,才可正常播放 |
| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite.<br>**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| | loop | boolean | 是 | 是 | 音频循环播放属性,设置为'true'表示循环播放。 |
| currentTime | number | Yes | No | Current audio playback position.<br>**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| | currentTime | number | 是 | 否 | 音频的当前播放位置。 |
| duration | number | Yes | No | Audio duration.<br>**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| | duration | number | 是 | 否 | 音频时长。 |
| state | [AudioState](#audiostate) | Yes | No | Audio playback state.<br>**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| | state | [AudioState](#audiostate) | 是 | 否 | 音频播放的状态。 |
### play<a name=audioplayer_play></a> ### play<a name=audioplayer_play></a>
play(): void play(): void
Starts to play audio resources. This method can be called only after the [dataLoad](#on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange')) event is triggered. 开始播放音频资源,需在[dataLoad](#on('play' | 'pause' | 'stop' | 'reset' | 'dataload' | 'finish' | 'volumechange'))事件成功触发后,才能调用play方法。
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer **示例:**
**Example**
```js ```js
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { //设置'play'事件回调
console.log('audio play success'); console.log('audio play success');
}); });
audioPlayer.play(); audioPlayer.play();
...@@ -294,14 +387,12 @@ audioPlayer.play(); ...@@ -294,14 +387,12 @@ audioPlayer.play();
pause(): void pause(): void
Pauses audio playback. 暂停播放音频资源。
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
**Example** **示例:**
```js ```js
audioPlayer.on('pause', () => { // Set the 'pause' event callback. audioPlayer.on('pause', () => { //设置'pause'事件回调
console.log('audio pause success'); console.log('audio pause success');
}); });
audioPlayer.pause(); audioPlayer.pause();
...@@ -311,14 +402,12 @@ audioPlayer.pause(); ...@@ -311,14 +402,12 @@ audioPlayer.pause();
stop(): void stop(): void
Stops audio playback. 停止播放音频资源。
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer **示例:**
**Example**
```js ```js
audioPlayer.on('stop', () => { // Set the 'stop' event callback. audioPlayer.on('stop', () => { //设置'stop'事件回调
console.log('audio stop success'); console.log('audio stop success');
}); });
audioPlayer.stop(); audioPlayer.stop();
...@@ -328,14 +417,12 @@ audioPlayer.stop(); ...@@ -328,14 +417,12 @@ audioPlayer.stop();
reset(): void reset(): void
Switches the audio resource to be played. 切换播放音频资源。
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
**Example** **示例:**
```js ```js
audioPlayer.on('reset', () => { // Set the 'reset' event callback. audioPlayer.on('reset', () => { //设置'reset'事件回调
console.log('audio reset success'); console.log('audio reset success');
}); });
audioPlayer.reset(); audioPlayer.reset();
...@@ -345,61 +432,55 @@ audioPlayer.reset(); ...@@ -345,61 +432,55 @@ audioPlayer.reset();
seek(timeMs: number): void 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.| | timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 |
**Example** **示例:**
```js ```js
audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调
if (typeof (seekDoneTime) == 'undefined') { if (typeof (seekDoneTime) == 'undefined') {
console.info('audio seek fail'); console.info('audio seek fail');
return; return;
} }
console.log('audio seek success. seekDoneTime: ' + seekDoneTime); console.log('audio seek success. seekDoneTime: ' + seekDoneTime);
}); });
audioPlayer.seek(30000); // Seek to 30000 ms. audioPlayer.seek(30000); //seek到30000ms的位置
``` ```
### setVolume<a name=audioplayer_setvolume></a> ### setVolume<a name=audioplayer_setvolume></a>
setVolume(vol: number): void 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%).| | vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 |
**Example** **示例:**
```js ```js
audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调
console.log('audio volumeChange success'); console.log('audio volumeChange success');
}); });
audioPlayer.setVolume(1); // Set the volume to 100%. audioPlayer.setVolume(1); //设置音量到100%
``` ```
### release<a name=audioplayer_release></a> ### release<a name=audioplayer_release></a>
release(): void release(): void
Releases the audio playback resource. 释放音频资源。
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
**Example** **示例:**
```js ```js
audioPlayer.release(); audioPlayer.release();
...@@ -410,17 +491,15 @@ audioPlayer = undefined; ...@@ -410,17 +491,15 @@ audioPlayer = undefined;
getTrackDescription(callback: AsyncCallback<Array<[MediaDescription](#mediadescription8)>>): void getTrackDescription(callback: AsyncCallback<Array<[MediaDescription](#mediadescription8)>>): void
Obtains the audio track information. This API uses a callback to return the result. 通过回调方式获取音频轨道信息。
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer **参数:**
**Parameters** | 参数名 | 类型 | 必填 | 说明 |
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | -------------------------- | | -------- | ------------------------------------------------------------ | ---- | -------------------------- |
| callback | AsyncCallback<Array<[MediaDescription](#mediadescription8)>> | Yes | Callback used to return the audio track information obtained.| | callback | AsyncCallback<Array<[MediaDescription](#mediadescription8)>> | 是 | 获取音频轨道信息回调方法。 |
**Example** **示例:**
```js ```js
function printfDescription(obj) { function printfDescription(obj) {
...@@ -446,17 +525,15 @@ audioPlayer.getTrackDescription((error, arrlist) => { ...@@ -446,17 +525,15 @@ audioPlayer.getTrackDescription((error, arrlist) => {
getTrackDescription(): Promise<Array<[MediaDescription](#mediadescription8)>> getTrackDescription(): Promise<Array<[MediaDescription](#mediadescription8)>>
Obtains the audio track information. This API uses a promise to return the result. 通过Promise方式获取音频轨道信息。
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| ------------------------------------------------------ | ------------------------------- | | ------------------------------------------------------ | ------------------------------- |
| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the audio track information obtained.| | Promise<Array<[MediaDescription](#mediadescription8)>> | 获取音频轨道信息Promise返回值。 |
**Example** **示例:**
```js ```js
function printfDescription(obj) { function printfDescription(obj) {
...@@ -489,18 +566,16 @@ for (let i = 0; i < arrayDescription.length; i++) { ...@@ -489,18 +566,16 @@ for (let i = 0; i < arrayDescription.length; i++) {
on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), 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. | | type | string | 是 | 音频缓存事件回调类型,支持的事件:'bufferingUpdate'。 |
| callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | Yes | Callback invoked when the event is triggered.<br>When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| | callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | 是 | 音频缓存事件回调方法。<br>[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 |
**Example** **示例:**
```js ```js
audioPlayer.on('bufferingUpdate', (infoType, value) => { audioPlayer.on('bufferingUpdate', (infoType, value) => {
...@@ -513,174 +588,154 @@ audioPlayer.on('bufferingUpdate', (infoType, value) => { ...@@ -513,174 +588,154 @@ audioPlayer.on('bufferingUpdate', (infoType, value) => {
on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void 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'<br>- The 'play' event is triggered when the [play()](#play) method is called and audio playback starts.<br>- The 'pause' event is triggered when the [pause()](#pause) method is called and audio playback is paused.<br>- The 'stop' event is triggered when the [stop()](#stop) method is called and audio playback stops.<br>- The 'reset' event is triggered when the [reset()](#reset7) method is called and audio playback is reset.<br>- The 'dataLoad' event is triggered when the audio data is loaded, that is, when the **src** attribute is configured.<br>- The 'finish' event is triggered when the audio playback is finished.<br>- The 'volumeChange' event is triggered when the [setVolume()](#setvolume) method is called and the playback volume is changed.| | type | string | 是 | 播放事件回调类型,支持的事件包括:'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'。<br>- 'play':完成[play()](#play)调用,音频开始播放,触发该事件。<br>- 'pause':完成[pause()](#pause)调用,音频暂停播放,触发该事件。<br>- 'stop':完成[stop()](#stop)调用,音频停止播放,触发该事件。<br>- 'reset':完成[reset()](#reset7)调用,播放器重置,触发该事件。<br>- 'dataLoad':完成音频数据加载后触发该事件,即src属性设置完成后触发该事件。<br>- 'finish':完成音频播放后触发该事件。<br>- 'volumeChange':完成[setVolume()](#setvolume)调用,播放音量改变后触发该事件。 |
| callback | () => void | Yes | Callback invoked when the event is triggered. | | callback | () => void | 是 | 播放事件回调方法。 |
**Example** **示例:**
```js ```js
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Start the playback and trigger the 'play' event callback. audioPlayer.play(); //开始播放,并触发'play'事件回调
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { //设置'play'事件回调
console.info('audio play success'); console.info('audio play success');
audioPlayer.seek(30000); // Call the seek() method and trigger the 'timeUpdate' event callback. audioPlayer.seek(30000); //调用seek方法,并触发'timeUpdate'事件回调
}); });
audioPlayer.on('pause', () => { // Set the 'pause' event callback. audioPlayer.on('pause', () => { //设置'pause'事件回调
console.info('audio pause success'); console.info('audio pause success');
audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. audioPlayer.stop(); //停止播放,并触发'stop'事件回调
}); });
audioPlayer.on('reset', () => { // Set the 'reset' event callback. audioPlayer.on('reset', () => { //设置'reset'事件回调
console.info('audio reset success'); console.info('audio reset success');
audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer.release(); //释放播放实例资源
audioPlayer = undefined; audioPlayer = undefined;
}); });
audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调
if (typeof(seekDoneTime) == "undefined") { if (typeof(seekDoneTime) == "undefined") {
console.info('audio seek fail'); console.info('audio seek fail');
return; return;
} }
console.info('audio seek success, and seek time is ' + seekDoneTime); 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.setVolume(0.5); //设置音量为50%,并触发'volumeChange'事件回调
}); });
audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调
console.info('audio volumeChange success'); console.info('audio volumeChange success');
audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. audioPlayer.pause(); //暂停播放,并触发'pause'事件回调
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback. audioPlayer.on('finish', () => { //设置'finish'事件回调
console.info('audio play finish'); console.info('audio play finish');
audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. audioPlayer.stop(); //停止播放,并触发'stop'事件回调
}); });
audioPlayer.on('error', (error) => { // Set the 'error' event callback. audioPlayer.on('error', (error) => { //设置'error'事件回调
console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`); console.info(`audio error called, errMessage is ${error.message}`);
}); });
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; //设置src属性,并触发'dataLoad'事件回调
// Set the FD (local playback) of the video file selected by the user.
let fdPath = 'fd://'
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
await 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('timeUpdate')
on(type: 'timeUpdate', callback: Callback\<number>): void on(type: 'timeUpdate', callback: Callback\<number>): void
Subscribes to the 'timeUpdate' event. 开始订阅音频播放[seek()](#seek)时间更新事件。
**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 method.<br>The 'timeUpdate' event is triggered when the [seek()](#seek) method is called.| | type | string | 是 | 播放事件回调类型,支持的事件包括:'timeUpdate'。<br>- 'timeUpdate':[seek()](#seek)调用完成,触发该事件。 |
| 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. | | callback | Callback\<number> | 是 | 播放事件回调方法。回调方法入参为成功seek的时间。 |
**Example** **示例:**
```js ```js
audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调
if (typeof (seekDoneTime) == 'undefined') { if (typeof (seekDoneTime) == 'undefined') {
console.info('audio seek fail'); console.info('audio seek fail');
return; return;
} }
console.log('audio seek success. seekDoneTime: ' + seekDoneTime); console.log('audio seek success. seekDoneTime: ' + seekDoneTime);
}); });
audioPlayer.seek(30000); // Seek to 30000 ms. audioPlayer.seek(30000); //seek到30000ms的位置
``` ```
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback): void 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 method.<br>The 'error' event is triggered when an error occurs during audio playback.| | type | string | 是 | 播放错误事件回调类型,支持的事件包括:'error'。<br>- 'error':音频播放中发生错误,触发该事件。 |
| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | | callback | ErrorCallback | 是 | 播放错误事件回调方法。 |
**Example** **示例:**
```js ```js
audioPlayer.on('error', (error) => { // Set the error event callback. audioPlayer.on('error', (error) => { //设置'error'事件回调
console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errName is ${error.name}`); //打印错误类型名称
console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errCode is ${error.code}`); //打印错误码
console.info(`audio error called, errMessage is ${error.message}`);// Print the detailed description of the error type. console.info(`audio error called, errMessage is ${error.message}`);//打印错误类型详细描述
}); });
audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. audioPlayer.setVolume(3); //设置volume为无效值,触发'error'事件
``` ```
## AudioState ## AudioState
Enumerates the audio playback states. You can obtain the state through the **state** attribute. 音频播放的状态机。可通过state属性获取当前状态。
| Name | Type | Description | | 名称 | 类型 | 描述 |
| ------------------ | ------ | ------------------------------------------------------------ | | ------------------ | ------ | -------------- |
| idle | string | The audio player is idle.<br>**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| | idle | string | 音频播放空闲。 |
| playing | string | Audio playback is in progress.<br>**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| | playing | string | 音频正在播放。 |
| paused | string | Audio playback is paused.<br>**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| | paused | string | 音频暂停播放。 |
| stopped | string | Audio playback is stopped.<br>**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| | stopped | string | 音频播放停止。 |
| error<sup>8+</sup> | string | Audio playback is in the error state.<br>**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| | error<sup>8+</sup> | string | 错误状态。 |
## VideoPlayer<sup>8+</sup> ## VideoPlayer<sup>8+</sup>
Provides methods to manage and play video. Before calling a method of the **VideoPlayer** class, you must call [createVideoPlayer()](#media.createvideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. 视频播放管理类,用于管理和播放视频媒体。在调用VideoPlayer的方法前,需要先通过[createVideoPlayer()](#media.createvideoplayer8)构建一个[VideoPlayer](#videoplayer8)实例。
For details about the video playback demo, see [Video Playback Development](../../media/video-playback.md). 视频播放demo可参考:[视频播放开发指导](../../media/video-playback.md)
### Attributes<a name=videoplayer_attributes></a> ### 属性<a name=videoplayer_属性></a><sup>8+</sup>
| Name | Type | Readable| Writable| Description | | 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | | ----------- | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| url<sup>8+</sup> | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.<br>**Example of supported URIs**:<br>1. FD playback: fd://xxx<br>![en-us_image_0000001164217678](figures/en-us_image_url.png)<br>**Note**:<br>To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | url | string | 是 | 是 | 视频媒体URL,支持当前主流的视频格式(mp4、mpeg-ts、webm、mkv)。<br>**支持路径示例**<br>1. 本地绝对路径:file:///data/data/ohos.xxx.xxx/files/test.mp4<br>![zh-cn_image_0000001164217678](figures/zh-cn_image_0000001164217678.png)<br>**注意事项**<br>媒体素材需至少赋予读权限后,才可正常播放 |
| loop<sup>8+</sup> | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | loop | boolean | 是 | 是 | 视频循环播放属性,设置为'true'表示循环播放。 |
| currentTime<sup>8+</sup> | number | Yes | No | Current video playback position.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | currentTime | number | 是 | 否 | 视频的当前播放位置。 |
| duration<sup>8+</sup> | number | Yes | No | Video duration. The value **-1** indicates the live streaming mode.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | duration | number | 是 | 否 | 视频时长,返回-1表示直播模式 |
| state<sup>8+</sup> | [VideoPlayState](#videoplaystate8) | Yes | No | Video playback state.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | state | [VideoPlayState](#videoplaystate8) | 是 | 否 | 视频播放的状态。 |
| width<sup>8+</sup> | number | Yes | No | Video width.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | width | number | 是 | 否 | 视频宽。 |
| height<sup>8+</sup> | number | Yes | No | Video height.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | height | number | 是 | 否 | 视频高。 |
### setDisplaySurface<sup>8+</sup> ### setDisplaySurface<sup>8+</sup>
setDisplaySurface(surfaceId: string, callback: AsyncCallback\<void>): void setDisplaySurface(surfaceId: string, callback: AsyncCallback\<void>): void
Sets **SurfaceId**. This API uses a callback to return the result. 通过回调方式设置SurfaceId。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
**Parameters** **参数:**
| Name | Type | Mandatory| Description | | 参数名 | 类型 | 必填 | 说明 |
| --------- | -------- | ---- | ------------------------- | | --------- | -------- | ---- | ------------------------- |
| surfaceId | string | Yes | Surface ID to set. | | surfaceId | string | 是 | SurfaceId |
| callback | function | Yes | Callback used to set **SurfaceId**.| | callback | function | 是 | 设置SurfaceId的回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.setDisplaySurface(surfaceId, (err) => { videoPlayer.setDisplaySurface(surfaceId, (err) => {
...@@ -696,23 +751,21 @@ videoPlayer.setDisplaySurface(surfaceId, (err) => { ...@@ -696,23 +751,21 @@ videoPlayer.setDisplaySurface(surfaceId, (err) => {
setDisplaySurface(surfaceId: string): Promise\<void> setDisplaySurface(surfaceId: string): Promise\<void>
Sets **SurfaceId**. This API uses a promise to return the result. 通过Promise方式设置SurfaceId。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer **参数:**
**Parameters** | 参数名 | 类型 | 必填 | 说明 |
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | --------- | | --------- | ------ | ---- | --------- |
| surfaceId | string | Yes | Surface ID to set.| | surfaceId | string | 是 | SurfaceId |
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| ------------- | ------------------------------ | | ------------- | ------------------------------ |
| Promise<void> | Promise used to set **SurfaceId**.| | Promise<void> | 设置SurfaceId的Promise返回值。 |
**Example** **示例:**
```js ```js
function failureCallback(error) { function failureCallback(error) {
...@@ -730,17 +783,15 @@ await videoPlayer.setDisplaySurface(surfaceId).then(() => { ...@@ -730,17 +783,15 @@ await videoPlayer.setDisplaySurface(surfaceId).then(() => {
prepare(callback: AsyncCallback\<void>): void 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.| | callback | function | 是 | 准备播放视频的回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.prepare((err) => { videoPlayer.prepare((err) => {
...@@ -756,17 +807,15 @@ videoPlayer.prepare((err) => { ...@@ -756,17 +807,15 @@ videoPlayer.prepare((err) => {
prepare(): Promise\<void> prepare(): Promise\<void>
Prepares for video playback. This API uses a promise to return the result. 通过Promise方式准备播放视频。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer **返回值:**
**Return value** | 类型 | 说明 |
| Type | Description |
| -------------- | ----------------------------- | | -------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 准备播放视频的Promise返回值。 |
**Example** **示例:**
```js ```js
function failureCallback(error) { function failureCallback(error) {
...@@ -784,17 +833,15 @@ await videoPlayer.prepare().then(() => { ...@@ -784,17 +833,15 @@ await videoPlayer.prepare().then(() => {
play(callback: AsyncCallback\<void>): void; 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.| | callback | function | 是 | 开始播放视频的回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.play((err) => { videoPlayer.play((err) => {
...@@ -810,17 +857,15 @@ videoPlayer.play((err) => { ...@@ -810,17 +857,15 @@ videoPlayer.play((err) => {
play(): Promise\<void>; play(): Promise\<void>;
Starts to play video resources. This API uses a promise to return the result. 通过Promise方式开始播放视频。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer **返回值:**
**Return value** | 类型 | 说明 |
| Type | Description |
| -------------- | ----------------------------- | | -------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 开始播放视频的Promise返回值。 |
**Example** **示例:**
```js ```js
function failureCallback(error) { function failureCallback(error) {
...@@ -838,17 +883,15 @@ await videoPlayer.play().then(() => { ...@@ -838,17 +883,15 @@ await videoPlayer.play().then(() => {
pause(callback: AsyncCallback\<void>): void 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.| | callback | function | 是 | 暂停播放视频的回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.pause((err) => { videoPlayer.pause((err) => {
...@@ -864,17 +907,15 @@ videoPlayer.pause((err) => { ...@@ -864,17 +907,15 @@ videoPlayer.pause((err) => {
pause(): Promise\<void> pause(): Promise\<void>
Pauses video playback. This API uses a promise to return the result. 通过Promise方式暂停播放视频。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer **返回值:**
**Return value** | 类型 | 说明 |
| Type | Description |
| -------------- | ----------------------------- | | -------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 暂停播放视频的Promise返回值。 |
**Example** **示例:**
```js ```js
function failureCallback(error) { function failureCallback(error) {
...@@ -892,17 +933,15 @@ await videoPlayer.pause().then(() => { ...@@ -892,17 +933,15 @@ await videoPlayer.pause().then(() => {
stop(callback: AsyncCallback\<void>): void 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.| | callback | function | 是 | 停止播放视频的回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.stop((err) => { videoPlayer.stop((err) => {
...@@ -918,17 +957,15 @@ videoPlayer.stop((err) => { ...@@ -918,17 +957,15 @@ videoPlayer.stop((err) => {
stop(): Promise\<void> stop(): Promise\<void>
Stops video playback. This API uses a promise to return the result. 通过Promise方式停止播放视频。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| -------------- | ----------------------------- | | -------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 停止播放视频的Promise返回值。 |
**Example** **示例:**
```js ```js
function failureCallback(error) { function failureCallback(error) {
...@@ -946,17 +983,15 @@ await videoPlayer.stop().then(() => { ...@@ -946,17 +983,15 @@ await videoPlayer.stop().then(() => {
reset(callback: AsyncCallback\<void>): void 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.| | callback | function | 是 | 切换播放视频的回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.reset((err) => { videoPlayer.reset((err) => {
...@@ -972,17 +1007,15 @@ videoPlayer.reset((err) => { ...@@ -972,17 +1007,15 @@ videoPlayer.reset((err) => {
reset(): Promise\<void> reset(): Promise\<void>
Switches the video resource to be played. This API uses a promise to return the result. 通过Promise方式切换播放视频。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| -------------- | ----------------------------- | | -------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 切换播放视频的Promise返回值。 |
**Example** **示例:**
```js ```js
function failureCallback(error) { function failureCallback(error) {
...@@ -1000,18 +1033,16 @@ await videoPlayer.reset().then(() => { ...@@ -1000,18 +1033,16 @@ await videoPlayer.reset().then(() => {
seek(timeMs: number, callback: AsyncCallback\<number>): void 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.| | timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 |
| callback | function | Yes | Callback used to return the result.| | callback | function | 是 | 跳转到指定播放位置的回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.seek((seekTime, err) => { videoPlayer.seek((seekTime, err) => {
...@@ -1027,19 +1058,17 @@ videoPlayer.seek((seekTime, err) => { ...@@ -1027,19 +1058,17 @@ videoPlayer.seek((seekTime, err) => {
seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\<number>): void 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. | | timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 |
| mode | SeekMode | Yes | Seek mode. For details, see [SeekMode](#seekmode8).| | mode | SeekMode | 是 | 跳转模式,具体见[SeekMode](#seekmode8)|
| callback | function | Yes | Callback used to return the result. | | callback | function | 是 | 跳转到指定播放位置的回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.seek((seekTime, seekMode, err) => { videoPlayer.seek((seekTime, seekMode, err) => {
...@@ -1055,24 +1084,22 @@ videoPlayer.seek((seekTime, seekMode, err) => { ...@@ -1055,24 +1084,22 @@ videoPlayer.seek((seekTime, seekMode, err) => {
seek(timeMs: number, mode?:SeekMode): Promise\<number> 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. 通过Promise方式跳转到指定播放位置,如果没有设置mode则跳转到指定时间点的下一个关键帧。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer **参数:**
**Parameters** | 参数名 | 类型 | 必填 | 说明 |
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | -------------------------------------- | | ------ | -------- | ---- | -------------------------------------- |
| timeMs | number | Yes | Position to seek to, in milliseconds. | | timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 |
| mode | SeekMode | No | Seek mode. For details, see [SeekMode](#seekmode8).| | mode | SeekMode | 否 | 跳转模式,具体见[SeekMode](#seekmode8) |
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| -------------- | ----------------------------------- | | -------------- | ----------------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 跳转到指定播放位置的Promise返回值。 |
**Example** **示例:**
```js ```js
function failureCallback(error) { function failureCallback(error) {
...@@ -1081,7 +1108,7 @@ function failureCallback(error) { ...@@ -1081,7 +1108,7 @@ function failureCallback(error) {
function catchCallback(error) { function catchCallback(error) {
console.info(`video catchCallback, error:${error.message}`); console.info(`video catchCallback, error:${error.message}`);
} }
await videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime indicates the position after the seek operation is complete. await videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime表示seek完成后的时间点
console.info('seek success'); console.info('seek success');
}, failureCallback).catch(catchCallback); }, failureCallback).catch(catchCallback);
...@@ -1094,18 +1121,16 @@ await videoPlayer.seek(seekTime, seekMode).then((seekDoneTime) => { ...@@ -1094,18 +1121,16 @@ await videoPlayer.seek(seekTime, seekMode).then((seekDoneTime) => {
setVolume(vol: number, callback: AsyncCallback\<void>): void 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%).| | vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 |
| callback | function | Yes | Callback used to return the result. | | callback | function | 是 | 设置音量的回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.setVolume((vol, err) => { videoPlayer.setVolume((vol, err) => {
...@@ -1121,23 +1146,21 @@ videoPlayer.setVolume((vol, err) => { ...@@ -1121,23 +1146,21 @@ videoPlayer.setVolume((vol, err) => {
setVolume(vol: number): Promise\<void> setVolume(vol: number): Promise\<void>
Sets the volume. This API uses a promise to return the result. 通过Promise方式设置音量。
**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%).| | vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 |
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| -------------- | ------------------------- | | -------------- | ------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 设置音量的Promise返回值。 |
**Example** **示例:**
```js ```js
function failureCallback(error) { function failureCallback(error) {
...@@ -1155,17 +1178,15 @@ await videoPlayer.setVolume(vol).then() => { ...@@ -1155,17 +1178,15 @@ await videoPlayer.setVolume(vol).then() => {
release(callback: AsyncCallback\<void>): void 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.| | callback | function | 是 | 释放视频资源的回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.release((err) => { videoPlayer.release((err) => {
...@@ -1181,17 +1202,15 @@ videoPlayer.release((err) => { ...@@ -1181,17 +1202,15 @@ videoPlayer.release((err) => {
release(): Promise\<void> release(): Promise\<void>
Releases the video playback resource. This API uses a promise to return the result. 通过Promise方式释放视频资源。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| -------------- | ----------------------------- | | -------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 释放视频资源的Promise返回值。 |
**Example** **示例:**
```js ```js
function failureCallback(error) { function failureCallback(error) {
...@@ -1209,17 +1228,15 @@ await videoPlayer.release().then() => { ...@@ -1209,17 +1228,15 @@ await videoPlayer.release().then() => {
getTrackDescription(callback: AsyncCallback<Array<[MediaDescription](#mediadescription8>>)>>): void getTrackDescription(callback: AsyncCallback<Array<[MediaDescription](#mediadescription8>>)>>): 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 | function | Yes | Callback used to return the video track information obtained.| | callback | function | 是 | 获取视频轨道信息回调方法。 |
**Example** **示例:**
```js ```js
function printfDescription(obj) { function printfDescription(obj) {
...@@ -1245,17 +1262,15 @@ videoPlayer.getTrackDescription((error, arrlist) => { ...@@ -1245,17 +1262,15 @@ videoPlayer.getTrackDescription((error, arrlist) => {
getTrackDescription(): Promise<Array<[MediaDescription](#mediadescription8>>)>> getTrackDescription(): Promise<Array<[MediaDescription](#mediadescription8>>)>>
Obtains the video track information. This API uses a promise to return the result. 通过Promise方式获取视频轨道信息。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| -------------------------------------------------------- | ------------------------------- | | -------------------------------------------------------- | ------------------------------- |
| Promise<Array<[MediaDescription](#mediadescription8>>)>> | Promise used to return the video track information obtained.| | Promise<Array<[MediaDescription](#mediadescription8>>)>> | 获取视频轨道信息Promise返回值。 |
**Example** **示例:**
```js ```js
function printfDescription(obj) { function printfDescription(obj) {
...@@ -1289,18 +1304,16 @@ for (let i = 0; i < arrayDescription.length; i++) { ...@@ -1289,18 +1304,16 @@ for (let i = 0; i < arrayDescription.length; i++) {
setSpeed(speed:number, callback: AsyncCallback\<number>): void 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](#playbackspeed8).| | speed | number | 是 | 指定播放视频速度,具体见[PlaybackSpeed](#playbackspeed8)|
| callback | function | Yes | Callback used to return the result. | | callback | function | 是 | 设置播放速度的回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.setSpeed((speed:number, err) => { videoPlayer.setSpeed((speed:number, err) => {
...@@ -1316,17 +1329,15 @@ videoPlayer.setSpeed((speed:number, err) => { ...@@ -1316,17 +1329,15 @@ videoPlayer.setSpeed((speed:number, err) => {
setSpeed(speed:number): Promise\<number> setSpeed(speed:number): Promise\<number>
Sets the video playback speed. This API uses a promise to return the result. 通过Promise方式设置播放速度。
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
**Parameters** **参数:**
| Name| Type | Mandatory| Description | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ---------------------------------------------------------- | | ------ | ------ | ---- | ---------------------------------------------------------- |
| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| | speed | number | 是 | 指定播放视频速度,具体见[PlaybackSpeed](#playbackspeed8)|
**Example** **示例:**
```js ```js
function failureCallback(error) { function failureCallback(error) {
...@@ -1344,18 +1355,16 @@ await videoPlayer.setSpeed(speed).then() => { ...@@ -1344,18 +1355,16 @@ await videoPlayer.setSpeed(speed).then() => {
on(type: 'playbackCompleted', callback: Callback\<void>): void 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.| | type | string | 是 | 视频播放完成事件回调类型,支持的事件:'playbackCompleted'。 |
| callback | function | Yes | Callback invoked when the event is triggered. | | callback | function | 是 | 视频播放完成事件回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.on('playbackCompleted', () => { videoPlayer.on('playbackCompleted', () => {
...@@ -1367,18 +1376,16 @@ videoPlayer.on('playbackCompleted', () => { ...@@ -1367,18 +1376,16 @@ videoPlayer.on('playbackCompleted', () => {
on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void 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. | | type | string | 是 | 视频缓存事件回调类型,支持的事件:'bufferingUpdate'。 |
| callback | function | Yes | Callback invoked when the event is triggered.<br>When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| | callback | function | 是 | 视频缓存事件回调方法。<br>[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 |
**Example** **示例:**
```js ```js
videoPlayer.on('bufferingUpdate', (infoType, value) => { videoPlayer.on('bufferingUpdate', (infoType, value) => {
...@@ -1391,18 +1398,16 @@ videoPlayer.on('bufferingUpdate', (infoType, value) => { ...@@ -1391,18 +1398,16 @@ videoPlayer.on('bufferingUpdate', (infoType, value) => {
on(type: 'startRenderFrame', callback: Callback\<void>): void 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.| | type | string | 是 | 视频播放首帧送显上报事件回调类型,支持的事件:'startRenderFrame'。 |
| callback | function | Yes | Callback invoked when the event is triggered. | | callback | function | 是 | 视频播放首帧送显上报事件回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.on('startRenderFrame', () => { videoPlayer.on('startRenderFrame', () => {
...@@ -1414,18 +1419,16 @@ videoPlayer.on('startRenderFrame', () => { ...@@ -1414,18 +1419,16 @@ videoPlayer.on('startRenderFrame', () => {
on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void 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.| | type | string | 是 | 视频播放宽高变化事件回调类型,支持的事件:'videoSizeChanged'。 |
| callback | function | Yes | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height. | | callback | function | 是 | 视频播放宽高变化事件回调方法,width表示宽,height表示高。 |
**Example** **示例:**
```js ```js
videoPlayer.on('videoSizeChanged', (width, height) => { videoPlayer.on('videoSizeChanged', (width, height) => {
...@@ -1438,74 +1441,74 @@ videoPlayer.on('videoSizeChanged', (width, height) => { ...@@ -1438,74 +1441,74 @@ videoPlayer.on('videoSizeChanged', (width, height) => {
on(type: 'error', callback: ErrorCallback): void 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 method.<br>The 'error' event is triggered when an error occurs during video playback.| | type | string | 是 | 播放错误事件回调类型,支持的事件包括:'error'。<br>- 'error':视频播放中发生错误,触发该事件。 |
| callback | function | Yes | Callback invoked when the event is triggered. | | callback | function | 是 | 播放错误事件回调方法。 |
**Example** **示例:**
```js ```js
videoPlayer.on('error', (error) => { // Set the 'error' event callback. videoPlayer.on('error', (error) => { // 设置'error'事件回调
console.info(`video error called, errName is ${error.name}`); // Print the error name. console.info(`video error called, errName is ${error.name}`); // 打印错误类型名称
console.info(`video error called, errCode is ${error.code}`); // Print the error code. console.info(`video error called, errCode is ${error.code}`); // 打印错误码
console.info(`video error called, errMessage is ${error.message}`);// Print the detailed description of the error type. console.info(`video error called, errMessage is ${error.message}`);// 打印错误类型详细描述
}); });
videoPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. videoPlayer.setVolume(3); //设置volume为无效值,触发'error'事件
``` ```
## VideoPlayState<sup>8+</sup> ## VideoPlayState<sup>8+</sup>
Enumerates the video playback states. You can obtain the state through the **state** attribute. 视频播放的状态机,可通过state属性获取当前状态。
| Name | Type | Description | | 名称 | 类型 | 描述 |
| -------- | ------ | ------------------------------------------------------------ | | -------- | ------ | -------------- |
| idle | string | The video player is idle.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | idle | string | 视频播放空闲。 |
| prepared | string | Video playback is being prepared.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | prepared | string | 视频播放准备。 |
| playing | string | Video playback is in progress.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | playing | string | 视频正在播放。 |
| paused | string | Video playback is paused.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | paused | string | 视频暂停播放。 |
| stopped | string | Video playback is stopped.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | stopped | string | 视频播放停止。 |
| error | string | Video playback is in the error state.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | error | string | 错误状态。 |
## SeekMode<sup>8+</sup> ## SeekMode<sup>8+</sup>
Enumerates the video playback seek modes, which can be passed in the **seek** method. 视频播放的Seek模式枚举,可通过seek方法作为参数传递下去。
| 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.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | SEEK_NEXT_SYNC | 0 | 表示跳转到指定时间点的下一个关键帧,建议向后快进的时候用这个枚举值 |
| 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.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | SEEK_PREV_SYNC | 1 | 表示跳转到指定时间点的上一个关键帧,建议向前快进的时候用这个枚举值 |
| SEEK_CLOSEST_SYNC | 2 | 表示跳转到指定时间点最近的关键帧。 |
| SEEK_CLOSEST | 3 | 表示精确跳转到指定时间点。 |
## PlaybackSpeed<sup>8+</sup> ## PlaybackSpeed<sup>8+</sup>
Enumerates the video playback speeds, which can be passed in the **setSpeed** method. 视频播放的倍速枚举,可通过setSpeed方法作为参数传递下去。
| Name | Value | Description | | 名称 | 值 | 描述 |
| -------------------- | ---- | ------------------------------------------------------------ | | -------------------- | ---- | ------------------------------ |
| SPEED_FORWARD_0_75_X | 0 | Plays the video at 0.75 times the normal speed.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | SPEED_FORWARD_0_75_X | 0 | 表示视频播放正常播速的0.75倍。 |
| SPEED_FORWARD_1_00_X | 1 | Plays the video at the normal speed.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | SPEED_FORWARD_1_00_X | 1 | 表示视频播放正常播速。 |
| SPEED_FORWARD_1_25_X | 2 | Plays the video at 1.25 times the normal speed.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | SPEED_FORWARD_1_25_X | 2 | 表示视频播放正常播速的1.25倍。 |
| SPEED_FORWARD_1_75_X | 3 | Plays the video at 1.75 times the normal speed.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | SPEED_FORWARD_1_75_X | 3 | 表示视频播放正常播速的1.75倍。 |
| SPEED_FORWARD_2_00_X | 4 | Plays the video at 2.00 times the normal speed.<br>**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| | SPEED_FORWARD_2_00_X | 4 | 表示视频播放正常播速的2.00倍。 |
## MediaDescription<sup>8+</sup> ## MediaDescription<sup>8+</sup>
### [key : string] : any ### [key : string] : any
Defines media information in key-value mode. 通过key-value方式获取媒体信息
| Name | Type | Description | | 名称 | 类型 | 说明 |
| ----- | ------ | ------------------------------------------------------------ | | ----- | ------ | ------------------------------------------------------------ |
| key | string | Key of the media information. For details about the keys, see [MediaDescriptionKey](#mediadescriptionkey8).<br>**System capability**: SystemCapability.Multimedia.Media.Core| | key | string | 通过key值获取对应的value。key值具体可见[MediaDescriptionKey](#mediadescriptionkey8)|
| value | any | Value of the key. For details about the values, see [MediaDescriptionKey](#mediadescriptionkey8).<br>**System capability**: SystemCapability.Multimedia.Media.Core| | value | any | 对应key值得value。其类型可为任意类型,具体key对应value的类型可参考[MediaDescriptionKey](#mediadescriptionkey8)的描述信息。 |
**Example** **示例:**
```js ```js
function printfItemDescription(obj, key) { function printfItemDescription(obj, key) {
...@@ -1517,7 +1520,7 @@ function printfItemDescription(obj, key) { ...@@ -1517,7 +1520,7 @@ function printfItemDescription(obj, key) {
audioPlayer.getTrackDescription((error, arrlist) => { audioPlayer.getTrackDescription((error, arrlist) => {
if (typeof (arrlist) != 'undefined') { if (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) { 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. printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE); //打印出每条轨道MD_KEY_TRACK_TYPE的值
} }
} else { } else {
console.log(`audio getTrackDescription fail, error:${error.message}`); console.log(`audio getTrackDescription fail, error:${error.message}`);
...@@ -1527,27 +1530,23 @@ audioPlayer.getTrackDescription((error, arrlist) => { ...@@ -1527,27 +1530,23 @@ audioPlayer.getTrackDescription((error, arrlist) => {
## AudioRecorder ## AudioRecorder
Implements audio recording. Before calling a method of the **AudioRecorder** class, you must call [createAudioRecorder()](#media.createaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. 音频录制管理类,用于录制音频媒体。在调用AudioRecorder的方法前,需要先通过[createAudioRecorder()](#media.createaudiorecorder)[createAudioRecorderAsync()](#media.createaudiorecorderasync8)构建一个[AudioRecorder](#audiorecorder)实例。
For details about the audio recording demo, see [Audio Recording Development](../../media/audio-recorder.md). 音频录制demo可参考:[音频录制开发指导](../../media/audio-recorder.md)
### prepare<a name=audiorecorder_prepare></a> ### prepare<a name=audiorecorder_prepare></a>
prepare(config: AudioRecorderConfig): void 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](#audiorecorderconfig) | Yes | Audio recording parameters, including the audio output URI, [encoding format](#audioencoder), sampling rate, number of audio channels, and [output format](#audiooutputformat).| | config | [AudioRecorderConfig](#audiorecorderconfig) | 是 | 配置录音的相关参数,包括音频输出URI、[编码格式](#audioencoder)、采样率、声道数、[输出格式](#audiooutputformat)等。 |
**Example** **示例:**
```js ```js
let audioRecorderConfig = { let audioRecorderConfig = {
...@@ -1556,10 +1555,10 @@ let audioRecorderConfig = { ...@@ -1556,10 +1555,10 @@ let audioRecorderConfig = {
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS, format : media.AudioOutputFormat.AAC_ADTS,
uri : 'fd://1', // The file must be created by the caller and granted with proper permissions. uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', // 文件需先由调用者创建,并给予适当的权限
location : { latitude : 30, longitude : 130}, location : { latitude : 30, longitude : 130},
} }
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. audioRecorder.on('prepare', () => { //设置'prepare'事件回调
console.log('prepare success'); console.log('prepare success');
}); });
audioRecorder.prepare(audioRecorderConfig); audioRecorder.prepare(audioRecorderConfig);
...@@ -1570,14 +1569,12 @@ audioRecorder.prepare(audioRecorderConfig); ...@@ -1570,14 +1569,12 @@ audioRecorder.prepare(audioRecorderConfig);
start(): void start(): void
Starts audio recording. This method can be called only after the [prepare](#audiorecorder_on) event is triggered. 开始录制,需在[prepare](#audiorecorder_on)事件成功触发后,才能调用start方法。
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
**Example** **示例:**
```js ```js
audioRecorder.on('start', () => { // Set the 'start' event callback. audioRecorder.on('start', () => { //设置'start'事件回调
console.log('audio recorder start success'); console.log('audio recorder start success');
}); });
audioRecorder.start(); audioRecorder.start();
...@@ -1587,14 +1584,12 @@ audioRecorder.start(); ...@@ -1587,14 +1584,12 @@ audioRecorder.start();
pause():void pause():void
Pauses audio recording. This method can be called only after the [start](#audiorecorder_on) event is triggered. 暂停录制,需要在[start](#audiorecorder_on)事件成功触发后,才能调用pause方法。
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder **示例:**
**Example**
```js ```js
audioRecorder.on('pause', () => { // Set the 'pause' event callback. audioRecorder.on('pause', () => { //设置'pause'事件回调
console.log('audio recorder pause success'); console.log('audio recorder pause success');
}); });
audioRecorder.pause(); audioRecorder.pause();
...@@ -1604,14 +1599,12 @@ audioRecorder.pause(); ...@@ -1604,14 +1599,12 @@ audioRecorder.pause();
resume():void resume():void
Resumes audio recording. This method can be called only after the [pause](#audiorecorder_on) event is triggered. 暂停录制,需要在[pause](#audiorecorder_on)事件成功触发后,才能调用resume方法。
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
**Example** **示例:**
```js ```js
audioRecorder.on('resume', () => { // Set the 'resume' event callback. audioRecorder.on('resume', () => { //设置'resume'事件回调
console.log('audio recorder resume success'); console.log('audio recorder resume success');
}); });
audioRecorder.resume(); audioRecorder.resume();
...@@ -1621,14 +1614,12 @@ audioRecorder.resume(); ...@@ -1621,14 +1614,12 @@ audioRecorder.resume();
stop(): void stop(): void
Stops audio recording. 停止录音。
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder **示例:**
**Example**
```js ```js
audioRecorder.on('stop', () => { // Set the 'stop' event callback. audioRecorder.on('stop', () => { //设置'stop'事件回调
console.log('audio recorder stop success'); console.log('audio recorder stop success');
}); });
audioRecorder.stop(); audioRecorder.stop();
...@@ -1638,14 +1629,12 @@ audioRecorder.stop(); ...@@ -1638,14 +1629,12 @@ audioRecorder.stop();
release(): void release(): void
Releases the audio recording resource. 释放录音资源。
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
**Example** **示例:**
```js ```js
audioRecorder.on('release', () => { // Set the 'release' event callback. audioRecorder.on('release', () => { //设置'release'事件回调
console.log('audio recorder release success'); console.log('audio recorder release success');
}); });
audioRecorder.release(); audioRecorder.release();
...@@ -1656,16 +1645,14 @@ audioRecorder = undefined; ...@@ -1656,16 +1645,14 @@ audioRecorder = undefined;
reset(): void reset(): void
Resets audio recording. 重置录音。
Before resetting audio recording, you must call [stop()](#audiorecorder_stop) to stop recording. After audio recording is reset, you must call [prepare()](#audiorecorder_prepare) to set the recording parameters for another recording.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 进行重置录音之前,需要先调用[stop()](#audiorecorder_stop)停止录音。重置录音之后,需要调用[prepare()](#audiorecorder_prepare)设置录音参数项,才能再次进行录音。
**Example** **示例:**
```js ```js
audioRecorder.on('reset', () => { // Set the 'reset' event callback. audioRecorder.on('reset', () => { //设置'reset'事件回调
console.log('audio recorder reset success'); console.log('audio recorder reset success');
}); });
audioRecorder.reset(); audioRecorder.reset();
...@@ -1675,156 +1662,148 @@ audioRecorder.reset(); ...@@ -1675,156 +1662,148 @@ audioRecorder.reset();
on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void 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'<br>- The 'prepare' event is triggered when the [prepare](#audiorecorder_prepare) method is called and the audio recording parameters are set.<br>- The 'start' event is triggered when the [start](#audiorecorder_start) method is called and audio recording starts.<br>- The 'pause' event is triggered when the [pause](#audiorecorder_pause) method is called and audio recording is paused.<br>- The 'resume' event is triggered when the [resume](#audiorecorder_resume) method is called and audio recording is resumed.<br>- The 'stop' event is triggered when the [stop](#audiorecorder_stop) method is called and audio recording stops.<br>- The 'release' event is triggered when the [release](#audiorecorder_release) method is called and the recording resource is released.<br>- The 'reset' event is triggered when the [reset](#audiorecorder_reset) method is called and audio recording is reset.| | type | string | 是 | 录制事件回调类型,支持的事件包括:'prepare'&nbsp;\|&nbsp;'start'&nbsp;\| 'pause' \| ’resume‘ \|&nbsp;'stop'&nbsp;\|&nbsp;'release'&nbsp;\|&nbsp;'reset'。<br/>-&nbsp;'prepare'&nbsp;:完成[prepare](#audiorecorder_prepare)调用,音频录制参数设置完成,触发该事件。<br/>-&nbsp;'start'&nbsp;:完成[start](#audiorecorder_start)调用,音频录制开始,触发该事件。<br/>-&nbsp;'pause': 完成[pause](#audiorecorder_pause)调用,音频暂停录制,触发该事件。<br/>-&nbsp;'resume': 完成[resume](#audiorecorder_resume)调用,音频恢复录制,触发该事件。<br/>-&nbsp;'stop'&nbsp;:完成[stop](#audiorecorder_stop)调用,音频停止录制,触发该事件。<br/>-&nbsp;'release'&nbsp;:完成[release](#audiorecorder_release)调用,音频释放录制资源,触发该事件。<br/>-&nbsp;'reset':完成[reset](#audiorecorder_reset)调用,音频重置为初始状态,触发该事件。 |
| callback | ()=>void | Yes | Callback invoked when the event is triggered. | | callback | ()=>void | 是 | 录制事件回调方法。 |
**Example** **示例:**
```js ```js
let audiorecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. let audiorecorder = media.createAudioRecorder(); // 创建一个音频录制实例
let audioRecorderConfig = { let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC, , audioEncoder : media.AudioEncoder.AAC_LC, ,
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS, format : media.AudioOutputFormat.AAC_ADTS,
uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', // 文件需先由调用者创建,并给予适当的权限
location : { latitude : 30, longitude : 130}, location : { latitude : 30, longitude : 130},
} }
audioRecorder.on('error', (error) => { // Set the 'error' event callback. audioRecorder.on('error', (error) => { // 设置'error'事件回调
console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`); console.info(`audio error called, errMessage is ${error.message}`);
}); });
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. audioRecorder.on('prepare', () => { // 设置'prepare'事件回调
console.log('prepare success'); console.log('prepare success');
audioRecorder.start(); // Start recording and trigger the 'start' event callback. audioRecorder.start(); // 开始录制,并触发'start'事件回调
}); });
audioRecorder.on('start', () => { // Set the 'start' event callback. audioRecorder.on('start', () => { // 设置'start'事件回调
console.log('audio recorder start success'); console.log('audio recorder start success');
}); });
audioRecorder.on('pause', () => { // Set the 'pause' event callback. audioRecorder.on('pause', () => { // 设置'pause'事件回调
console.log('audio recorder pause success'); console.log('audio recorder pause success');
}); });
audioRecorder.on('resume', () => { // Set the 'resume' event callback. audioRecorder.on('resume', () => { // 设置'resume'事件回调
console.log('audio recorder resume success'); console.log('audio recorder resume success');
}); });
audioRecorder.on('stop', () => { // Set the 'stop' event callback. audioRecorder.on('stop', () => { // 设置'stop'事件回调
console.log('audio recorder stop success'); console.log('audio recorder stop success');
}); });
audioRecorder.on('release', () => { // Set the 'release' event callback. audioRecorder.on('release', () => { // 设置'release'事件回调
console.log('audio recorder release success'); console.log('audio recorder release success');
}); });
audioRecorder.on('reset', () => { // Set the 'reset' event callback. audioRecorder.on('reset', () => { // 设置'reset'事件回调
console.log('audio recorder reset success'); console.log('audio recorder reset success');
}); });
audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. audioRecorder.prepare(audioRecorderConfig) // 设置录制参数 ,并触发'prepare'事件回调
``` ```
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback): void 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 method.<br>The 'error' event is triggered when an error occurs during audio recording.| | type | string | 是 | 录制错误事件回调类型'error'。<br/>-&nbsp;'error':音频录制过程中发生错误,触发该事件。 |
| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | | callback | ErrorCallback | 是 | 录制错误事件回调方法。 |
**Example** **示例:**
```js ```js
audioRecorder.on('error', (error) => { // Set the 'error' event callback. audioRecorder.on('error', (error) => { // 设置'error'事件回调
console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errName is ${error.name}`); // 打印错误类型名称
console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errCode is ${error.code}`); // 打印错误码
console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. console.info(`audio error called, errMessage is ${error.message}`); // 打印错误类型详细描述
}); });
audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. audioRecorder.prepare(); // prepare不设置参数,触发'error'事件
``` ```
## AudioRecorderConfig ## AudioRecorderConfig
Describes audio recording configurations. 表示音频的录音配置。
| Name | Type | Mandatory| Description | | 名称 | 参数类型 | 必填 | 说明 |
| --------------------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | --------------------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| audioEncoder | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | audioEncoder | [AudioEncoder](#audioencoder) | 否 | 音频编码格式,默认设置为AAC_LC。 |
| audioEncodeBitRate | number | No | Audio encoding bit rate. The default value is **48000**.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | audioEncodeBitRate | number | 否 | 音频编码比特率,默认值为48000。 |
| audioSampleRate | number | No | Audio sampling rate. The default value is **48000**.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | audioSampleRate | number | 否 | 音频采集采样率,默认值为48000。 |
| numberOfChannels | number | No | Number of audio channels. The default value is **2**.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | numberOfChannels | number | 否 | 音频采集声道数,默认值为2。 |
| format | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | format | [AudioOutputFormat](#audiooutputformat) | 否 | 音量输出封装格式,默认设置为MPEG_4。 |
| location<sup>8+</sup> | [Location](#location8) | No | Geographical location of the recorded audio.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | location<sup>8+</sup> | [Location](#location8) | 否 | 音频采集的地理位置。 |
| uri | string | Yes | Audio output URI. Supported: fd://xx&nbsp;(fd&nbsp;number)<br>![en-us_image_0000001164217678](figures/en-us_image_url.png) <br>The file must be created by the caller and granted with proper permissions.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | uri | string | 是 | 音频输出URI。支持:<br/>1.&nbsp;文件的绝对路径:file:///data/data/ohos.xxx.xxx/cache/test.mp4![zh-cn_image_0000001164217678](figures/zh-cn_image_0000001164217678.png)<br/>2.&nbsp;文件的fd路径:file://1&nbsp;(fd&nbsp;number)<br/> 文件需要由调用者创建,并赋予适当的权限。 |
## AudioEncoder ## AudioEncoder
Enumerates the audio encoding formats. 表示音频编码格式的枚举。
| Name | Default Value| Description | | 名称 | 默认值 | 说明 |
| ------- | ------ | ------------------------------------------------------------ | | ------- | ------ | ------------------------------------------------------------ |
| DEFAULT | 0 | Default audio encoding format, which is Adaptive Multi Rate-Narrow Band Speech Codec (AMR-NB).<br>This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | DEFAULT | 0 | Default audio encoding format is AMR_NB。本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。<br/>**系统能力:**SystemCapability.Multimedia.Media.AudioRecorder |
| AMR_NB | 1 | AMR-NB.<br>This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | AMR_NB | 1 | AMR-NB(Adaptive Multi Rate-Narrow Band Speech Codec) 编码格式。本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。<br/>**系统能力:**SystemCapability.Multimedia.Media.AudioRecorder |
| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).<br>This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | AMR_WB | 2 | AMR-WB(Adaptive Multi Rate-Wide Band Speech Codec) 编码格式。本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。<br/>**系统能力:**SystemCapability.Multimedia.Media.AudioRecorder |
| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | AAC_LC | 3 | AAC-LC(Advanced&nbsp;Audio&nbsp;Coding&nbsp;Low&nbsp;Complexity)编码格式。<br/>**系统能力:**SystemCapability.Multimedia.Media.AudioRecorder |
| HE_AAC | 4 | High-Efficiency Advanced&nbsp;Audio&nbsp;Coding (HE_AAC).<br>This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | HE_AAC | 4 | HE_AAC(High-Efficiency Advanced&nbsp;Audio&nbsp;Coding)编码格式。本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。<br/>**系统能力:**SystemCapability.Multimedia.Media.AudioRecorder |
## AudioOutputFormat ## AudioOutputFormat
Enumerates the audio output formats. 表示音频封装格式的枚举。
| Name | Default Value| Description | | 名称 | 默认值 | 说明 |
| -------- | ------ | ------------------------------------------------------------ | | -------- | ------ | ------------------------------------------------------------ |
| DEFAULT | 0 | Default encapsulation format, which is MPEG-4.<br>This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | DEFAULT | 0 | 默认封装格式为MPEG-4。本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。<br/>**系统能力:**SystemCapability.Multimedia.Media.AudioRecorder |
| MPEG_4 | 2 | MPEG-4.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | MPEG_4 | 2 | 封装为MPEG-4格式。<br/>**系统能力:**SystemCapability.Multimedia.Media.AudioRecorder |
| AMR_NB | 3 | AMR_NB.<br>This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | AMR_NB | 3 | 封装为AMR_NB格式。本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。<br/>**系统能力:**SystemCapability.Multimedia.Media.AudioRecorder |
| AMR_WB | 4 | AMR_WB.<br>This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | AMR_WB | 4 | 封装为AMR_WB格式。本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。<br/>**系统能力:**SystemCapability.Multimedia.Media.AudioRecorder |
| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.<br>**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| | AAC_ADTS | 6 | 封装为ADTS(Audio&nbsp;Data&nbsp;Transport&nbsp;Stream)格式,是AAC音频的传输流格式。<br/>**系统能力:**SystemCapability.Multimedia.Media.AudioRecorder |
## VideoRecorder<sup>8+</sup> ## VideoRecorder<sup>8+</sup>
Implements video recording. Before calling a method of the **VideoRecorder** class, you must call [createVideoRecorder()](#media.createvideorecorder8) to create a [VideoRecorder](#videorecorder8) instance. 视频录制管理类,用于录制视频媒体。在调用VideoRecorder的方法前,需要先通过[createVideoRecorderAsync()](#media.createvideorecorderasync8)构建一个[VideoRecorder](#videorecorder8)实例。
For details about the video recording demo, see [Video Recording Development](../../media/video-recorder.md). 视频录制demo可参考:[视频录制开发指导](../../media/video-recorder.md)
### Attributes ### 属性
| Name | Type | Readable| Writable| Description | | 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------ | ------------------------------------- | ---- | ---- | ---------------- | | ----- | ------------------------------------- | ---- | ---- | ---------------- |
| state<sup>8+</sup> | [VideoRecordState](#videorecordstate) | Yes | No | Video recording state.| | state | [VideoRecordState](#videorecordstate) | 是 | 否 | 视频录制的状态。 |
### prepare<sup>8+</sup><a name=videorecorder_prepare1></a> ### prepare<a name=videorecorder_prepare1></a>
prepare(config: VideoRecorderConfig, callback: AsyncCallback\<void>): void; 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 ohos.permission.CAMERA **参数:**
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder | 参数名 | 类型 | 必填 | 说明 |
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | ----------------------------------- | | -------- | ------------------------------------------- | ---- | ----------------------------------- |
| config | [VideoRecorderConfig](#videorecorderconfig) | Yes | Video recording parameters to set. | | config | [VideoRecorderConfig](#videorecorderconfig) | 是 | 配置视频录制的相关参数。 |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void> | 是 | 异步视频录制prepare方法的回调方法。 |
**Example** **示例:**
```js ```js
let videoProfile = { let videoProfile = {
...@@ -1844,7 +1823,7 @@ let videoConfig = { ...@@ -1844,7 +1823,7 @@ let videoConfig = {
audioSourceType : 1, audioSourceType : 1,
videoSourceType : 0, videoSourceType : 0,
profile : videoProfile, profile : videoProfile,
url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. url : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.mp4', // 文件需先由调用者创建,并给予适当的权限
orientationHint : 0, orientationHint : 0,
location : { latitude : 30, longitude : 130 }, location : { latitude : 30, longitude : 130 },
} }
...@@ -1868,36 +1847,32 @@ media.createVideoRecorder((err, recorder) => { ...@@ -1868,36 +1847,32 @@ media.createVideoRecorder((err, recorder) => {
if (typeof (err) == 'undefined' && typeof (recorder) != 'undefined') { if (typeof (err) == 'undefined' && typeof (recorder) != 'undefined') {
videoRecorder = recorder; videoRecorder = recorder;
console.info('createVideoRecorder success'); console.info('createVideoRecorder success');
eventEmitter.emit('prepare'); // Trigger the 'prepare' event. eventEmitter.emit('prepare'); // prepare事件触发
} else { } else {
console.info('createVideoRecorder failed and error is ' + err.message); console.info('createVideoRecorder failed and error is ' + err.message);
} }
}); });
``` ```
### prepare<sup>8+</sup><a name=videorecorder_prepare2></a> ### prepare<a name=videorecorder_prepare2></a>
prepare(config: VideoRecorderConfig): Promise\<void>; prepare(config: VideoRecorderConfig): Promise\<void>;
Sets video recording parameters in asynchronous mode. This API uses a promise to return the result. 异步方式进行视频录制的参数设置。通过Promise获取返回值。
**Required permissions:** ohos.permission.MICROPHONE ohos.permission.CAMERA
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters** **参数:**
| Name| Type | Mandatory| Description | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------------------------------- | ---- | ------------------------ | | ------ | ------------------------------------------- | ---- | ------------------------ |
| config | [VideoRecorderConfig](#videorecorderconfig) | Yes | Video recording parameters to set.| | config | [VideoRecorderConfig](#videorecorderconfig) | 是 | 配置视频录制的相关参数。 |
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| -------------- | ---------------------------------------- | | -------------- | ---------------------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 异步视频录制prepare方法的Promise返回值。 |
**Example** **示例:**
```js ```js
let videoProfile = { let videoProfile = {
...@@ -1917,7 +1892,7 @@ let videoConfig = { ...@@ -1917,7 +1892,7 @@ let videoConfig = {
audioSourceType : 1, audioSourceType : 1,
videoSourceType : 0, videoSourceType : 0,
profile : videoProfile, profile : videoProfile,
url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. url : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.mp4', // 文件需先由调用者创建,并给予适当的权限
orientationHint : 0, orientationHint : 0,
location : { latitude : 30, longitude : 130 }, location : { latitude : 30, longitude : 130 },
} }
...@@ -1946,29 +1921,27 @@ await videoRecorder.prepare(videoConfig).then(() => { ...@@ -1946,29 +1921,27 @@ await videoRecorder.prepare(videoConfig).then(() => {
}); });
``` ```
### getInputSurface<sup>8+</sup> ### getInputSurface
getInputSurface(callback: AsyncCallback\<string>): void; 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. 异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的数据。
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. 应当注意,填入的视频数据需要携带时间戳(单位ns),buffersize。时间戳的起始时间请以系统启动时间为基准。
This method can be called only after [prepare()](#videorecorder_prepare1) is called. 只能在[prepare()](#videorecorder_prepare1)接口调用后调用。
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder **参数:**
**Parameters** | 参数名 | 类型 | 必填 | 说明 |
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | --------------------------- | | -------- | ---------------------- | ---- | --------------------------- |
| callback | AsyncCallback\<string> | Yes | Callback used to obtain the result.| | callback | AsyncCallback\<string> | 是 | 异步获得surface的回调方法。 |
**Example** **示例:**
```js ```js
// asyncallback // asyncallback
let surfaceID = null; // Surface ID passed to the external system. let surfaceID = null; // 传递给外界的surfaceID
videoRecorder.getInputSurface((err, surfaceId) => { videoRecorder.getInputSurface((err, surfaceId) => {
if (typeof (err) == 'undefined') { if (typeof (err) == 'undefined') {
console.info('getInputSurface success'); console.info('getInputSurface success');
...@@ -1979,29 +1952,27 @@ videoRecorder.getInputSurface((err, surfaceId) => { ...@@ -1979,29 +1952,27 @@ videoRecorder.getInputSurface((err, surfaceId) => {
}); });
``` ```
### getInputSurface<sup>8+</sup> ### getInputSurface
getInputSurface(): Promise\<string>; 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. 异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的数据。
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 method can be called only after [prepare()](#videorecorder_prepare1) is called. 应当注意,填入的视频数据需要携带时间戳(单位ns),buffersize。时间戳的起始时间请以系统启动时间为基准。
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder 只能在[prepare()](#videorecorder_prepare1)接口调用后调用。
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| ---------------- | -------------------------------- | | ---------------- | -------------------------------- |
| Promise\<string> | Promise used to return the result.| | Promise\<string> | 异步获得surface的Promise返回值。 |
**Example** **示例:**
```js ```js
// promise // promise
let surfaceID = null; // Surface ID passed to the external system. let surfaceID = null; // 传递给外界的surfaceID
await videoRecorder.getInputSurface().then((surfaceId) => { await videoRecorder.getInputSurface().then((surfaceId) => {
console.info('getInputSurface success'); console.info('getInputSurface success');
surfaceID = surfaceId; surfaceID = surfaceId;
...@@ -2012,23 +1983,21 @@ await videoRecorder.getInputSurface().then((surfaceId) => { ...@@ -2012,23 +1983,21 @@ await videoRecorder.getInputSurface().then((surfaceId) => {
}); });
``` ```
### start<sup>8+</sup><a name=videorecorder_start1></a> ### start<a name=videorecorder_start1></a>
start(callback: AsyncCallback\<void>): void; start(callback: AsyncCallback\<void>): void;
Starts video recording in asynchronous mode. This API uses a callback to return the result. 异步方式开始视频录制。通过注册回调函数获取返回值。
This method can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder [prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)后调用,需要依赖数据源先给surface传递数据。
**Parameters** **参数:**
| Name | Type | Mandatory| Description | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ---------------------------- | | -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void> | 是 | 异步开始视频录制的回调方法。 |
**Example** **示例:**
```js ```js
// asyncallback // asyncallback
...@@ -2041,23 +2010,21 @@ videoRecorder.start((err) => { ...@@ -2041,23 +2010,21 @@ videoRecorder.start((err) => {
}); });
``` ```
### start<sup>8+</sup><a name=videorecorder_start2></a> ### start<a name=videorecorder_start2></a>
start(): Promise\<void>; start(): Promise\<void>;
Starts video recording in asynchronous mode. This API uses a promise to return the result. 异步方式开始视频录制。通过Promise获取返回值。
This method can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first. [prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)后调用,需要依赖数据源先给surface传递数据。
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder **返回值:**
**Return value** | 类型 | 说明 |
| Type | Description |
| -------------- | ------------------------------------- | | -------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 异步开始视频录制方法的Promise返回值。 |
**Example** **示例:**
```js ```js
// promise // promise
...@@ -2070,23 +2037,21 @@ await videoRecorder.start().then(() => { ...@@ -2070,23 +2037,21 @@ await videoRecorder.start().then(() => {
}); });
``` ```
### pause<sup>8+</sup><a name=videorecorder_pause1></a> ### pause<a name=videorecorder_pause1></a>
pause(callback: AsyncCallback\<void>): void; pause(callback: AsyncCallback\<void>): void;
Pauses video recording in asynchronous mode. This API uses a callback to return the result. 异步方式暂停视频录制。通过注册回调函数获取返回值。
This method can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1).
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder [start()](#videorecorder_start1)后调用。可以通过调用[resume()](#videorecorder_resume1)接口来恢复录制。
**Parameters** **参数:**
| Name | Type | Mandatory| Description | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ---------------------------- | | -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void> | 是 | 异步暂停视频录制的回调方法。 |
**Example** **示例:**
```js ```js
// asyncallback // asyncallback
...@@ -2099,23 +2064,21 @@ videoRecorder.pause((err) => { ...@@ -2099,23 +2064,21 @@ videoRecorder.pause((err) => {
}); });
``` ```
### pause<sup>8+</sup><a name=videorecorder_pause2></a> ### pause<a name=videorecorder_pause2></a>
pause(): Promise\<void>; pause(): Promise\<void>;
Pauses video recording in asynchronous mode. This API uses a promise to return the result. 异步方式暂停视频录制。通过Promise获取返回值。
This method can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). [start()](#videorecorder_start1)后调用。可以通过调用[resume()](#videorecorder_resume1)接口来恢复录制。
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder **返回值:**
**Return value** | 类型 | 说明 |
| Type | Description |
| -------------- | ------------------------------------- | | -------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 异步暂停视频录制方法的Promise返回值。 |
**Example** **示例:**
```js ```js
// promise // promise
...@@ -2128,21 +2091,19 @@ await videoRecorder.pause().then(() => { ...@@ -2128,21 +2091,19 @@ await videoRecorder.pause().then(() => {
}); });
``` ```
### resume<sup>8+</sup><a name=videorecorder_resume1></a> ### resume<a name=videorecorder_resume1></a>
resume(callback: AsyncCallback\<void>): void; 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.| | callback | AsyncCallback\<void> | 是 | 异步恢复视频录制的回调方法。 |
**Example** **示例:**
```js ```js
// asyncallback // asyncallback
...@@ -2155,21 +2116,19 @@ videoRecorder.resume((err) => { ...@@ -2155,21 +2116,19 @@ videoRecorder.resume((err) => {
}); });
``` ```
### resume<sup>8+</sup><a name=videorecorder_resume2></a> ### resume<a name=videorecorder_resume2></a>
resume(): Promise\<void>; resume(): Promise\<void>;
Resumes video recording in asynchronous mode. This API uses a promise to return the result. 异步方式恢复视频录制。通过Promise获取返回值。
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder **返回值:**
**Return value** | 类型 | 说明 |
| Type | Description |
| -------------- | ------------------------------------- | | -------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 异步恢复视频录制方法的Promise返回值。 |
**Example** **示例:**
```js ```js
// promise // promise
...@@ -2182,23 +2141,21 @@ await videoRecorder.resume().then(() => { ...@@ -2182,23 +2141,21 @@ await videoRecorder.resume().then(() => {
}); });
``` ```
### stop<sup>8+</sup><a name=videorecorder_stop1></a> ### stop<a name=videorecorder_stop1></a>
stop(callback: AsyncCallback\<void>): void; 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()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder 需要重新调用[prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)接口才能重新录制。
**Parameters** **参数:**
| Name | Type | Mandatory| Description | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ---------------------------- | | -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void> | 是 | 异步停止视频录制的回调方法。 |
**Example** **示例:**
```js ```js
// asyncallback // asyncallback
...@@ -2211,23 +2168,21 @@ videoRecorder.stop((err) => { ...@@ -2211,23 +2168,21 @@ videoRecorder.stop((err) => {
}); });
``` ```
### stop<sup>8+</sup><a name=videorecorder_stop2></a> ### stop<a name=videorecorder_stop2></a>
stop(): Promise\<void>; stop(): Promise\<void>;
Stops video recording in asynchronous mode. This API uses a promise to return the result. 异步方式停止视频录制。通过Promise获取返回值。
To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. 需要重新调用[prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)接口才能重新录制。
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder **返回值:**
**Return value** | 类型 | 说明 |
| Type | Description |
| -------------- | ------------------------------------- | | -------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 异步停止视频录制方法的Promise返回值。 |
**Example** **示例:**
```js ```js
// promise // promise
...@@ -2240,21 +2195,19 @@ await videoRecorder.stop().then(() => { ...@@ -2240,21 +2195,19 @@ await videoRecorder.stop().then(() => {
}); });
``` ```
### release<sup>8+</sup><a name=videorecorder_release1></a> ### release<a name=videorecorder_release1></a>
release(callback: AsyncCallback\<void>): void; 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.| | callback | AsyncCallback\<void> | 是 | 异步释放视频录制资源的回调方法。 |
**Example** **示例:**
```js ```js
// asyncallback // asyncallback
...@@ -2267,21 +2220,19 @@ videoRecorder.release((err) => { ...@@ -2267,21 +2220,19 @@ videoRecorder.release((err) => {
}); });
``` ```
### release<sup>8+</sup><a name=videorecorder_release2></a> ### release<a name=videorecorder_release2></a>
release(): Promise\<void>; release(): Promise\<void>;
Releases the video recording resource in asynchronous mode. This API uses a promise to return the result. 异步方式释放视频录制资源。通过Promise获取返回值。
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| -------------- | ----------------------------------------- | | -------------- | ----------------------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 异步释放视频录制资源方法的Promise返回值。 |
**Example** **示例:**
```js ```js
// promise // promise
...@@ -2294,23 +2245,21 @@ await videoRecorder.release().then(() => { ...@@ -2294,23 +2245,21 @@ await videoRecorder.release().then(() => {
}); });
``` ```
### reset<sup>8+</sup><a name=videorecorder_reset1></a> ### reset<a name=videorecorder_reset1></a>
reset(callback: AsyncCallback\<void>): void; 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()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. 需要重新调用[prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)接口才能重新录制。
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder **参数:**
**Parameters** | 参数名 | 类型 | 必填 | 说明 |
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------------------- | | -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void> | 是 | 异步重置视频录制的回调方法。 |
**Example** **示例:**
```js ```js
// asyncallback // asyncallback
...@@ -2323,23 +2272,21 @@ videoRecorder.reset((err) => { ...@@ -2323,23 +2272,21 @@ videoRecorder.reset((err) => {
}); });
``` ```
### reset<sup>8+</sup><a name=videorecorder_reset2></a> ### reset<a name=videorecorder_reset2></a>
reset(): Promise\<void>; reset(): Promise\<void>;
Resets video recording in asynchronous mode. This API uses a promise to return the result. 异步方式重置视频录制。通过Promise获取返回值。
To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder 需要重新调用[prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)接口才能重新录制。
**Return value** **返回值:**
| Type | Description | | 类型 | 说明 |
| -------------- | ------------------------------------- | | -------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | 异步重置视频录制方法的Promise返回值。 |
**Example** **示例:**
```js ```js
// promise // promise
...@@ -2352,105 +2299,103 @@ await videoRecorder.reset().then(() => { ...@@ -2352,105 +2299,103 @@ await videoRecorder.reset().then(() => {
}); });
``` ```
### on('error')<sup>8+</sup> ### on('error')
on(type: 'error', callback: ErrorCallback): void 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 method.<br>The 'error' event is triggered when an error occurs during video recording.| | type | string | 是 | 录制错误事件回调类型'error'。<br/>-&nbsp;'error':音频录制过程中发生错误,触发该事件。 |
| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | | callback | ErrorCallback | 是 | 录制错误事件回调方法。 |
**Example** **示例:**
```js ```js
videoRecorder.on('error', (error) => { // Set the 'error' event callback. videoRecorder.on('error', (error) => { // 设置'error'事件回调
console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errName is ${error.name}`); // 打印错误类型名称
console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errCode is ${error.code}`); // 打印错误码
console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. console.info(`audio error called, errMessage is ${error.message}`); // 打印错误类型详细描述
}); });
// This event is reported when an error occurs during the retrieval of videoRecordState. // 当获取videoRecordState接口出错时通过此订阅事件上报
``` ```
## VideoRecordState<sup>8+</sup> ## VideoRecordState<sup>8+</sup>
Enumerates the video recording states. You can obtain the state through the **state** attribute. 视频录制的状态机。可通过state属性获取当前状态。
| Name | Type | Description | | 名称 | 类型 | 描述 |
| -------- | ------ | ------------------------------------------------------------ | | -------- | ------ | ---------------------- |
| idle | string | The video recorder is idle.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | idle | string | 视频录制空闲。 |
| prepared | string | The video recording parameters are set.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | prepared | string | 视频录制参数设置完成。 |
| playing | string | Video recording is in progress.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | playing | string | 视频正在录制。 |
| paused | string | Video recording is paused.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | paused | string | 视频暂停录制。 |
| stopped | string | Video recording is stopped.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | stopped | string | 视频录制停止。 |
| error | string | Video recording is in the error state.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | error | string | 错误状态。 |
## VideoRecorderConfig<sup>8+</sup> ## VideoRecorderConfig<sup>8+</sup>
Describes the video recording parameters. 表示视频录制的参数设置。
| Name | Type | Mandatory| Description | | 名称 | 参数类型 | 必填 | 说明 |
| --------------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | | --------------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| audioSourceType | [AudioSourceType](#audiosourcetype<sup>8+</sup>) | Yes | Type of the audio source for video recording.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | audioSourceType | [AudioSourceType](#audiosourcetype<sup>8+</sup>) | 是 | 视频录制的音频源类型。 |
| videoSourceType | [VideoSourceType](#videosourcetype<sup>8+</sup>) | Yes | Type of the video source for video recording.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | videoSourceType | [VideoSourceType](#videosourcetype<sup>8+</sup>) | 是 | 视频录制的视频源类型。 |
| profile | [VideoRecorderProfile](#videorecorderprofile<sup>8+</sup>) | Yes | Video recording profile.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | profile | [VideoRecorderProfile](#videorecorderprofile<sup>8+</sup>) | 是 | 视频录制的profile。 |
| orientationHint | number | No | Rotation angle of the recorded video.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | orientationHint | number | 否 | 录制视频的旋转角度。 |
| location | [Location](#location8) | No | Geographical location of the recorded video.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | location | [Location](#location8) | 否 | 录制视频的地理位置。 |
| url | string | Yes | Video output URL. Supported: fd://xx&nbsp;(fd&nbsp;number)<br>![en-us_image_0000001164217678](figures/en-us_image_url.png) <br>The file must be created by the caller and granted with proper permissions.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | uri | string | 是 | 视频输出URI。支持:<br/>1.&nbsp;文件的绝对路径:file:///data/data/ohos.xxx.xxx/cache/test.mp4![zh-cn_image_0000001164217678](figures/zh-cn_image_0000001164217678.png)<br/>2.&nbsp;文件的fd路径:file://1&nbsp;(fd&nbsp;number)<br/> 文件需要由调用者创建,并赋予适当的权限。 |
## AudioSourceType<sup>8+</sup> ## AudioSourceType<sup>8+</sup>
Enumerates the audio source types for video recording. 表示视频录制中音频源类型的枚举。
| Name | Value | Description | | 名称 | 值 | 说明 |
| ------------------------- | ---- | ------------------------------------------------------------ | | -------------------------- | ---- | ---------------------- |
| AUDIO_SOURCE_TYPE_DEFAULT | 0 | Default audio input source.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | AUDIO_SOURCE_TYPE_DEFAULT0 | 0 | 默认的音频输入源类型。 |
| AUDIO_SOURCE_TYPE_MIC | 1 | Mic audio input source.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | AUDIO_SOURCE_TYPE_MIC | 1 | 表示MIC的音频输入源。 |
## VideoSourceType<sup>8+</sup> ## VideoSourceType<sup>8+</sup>
Enumerates the video source types for video recording. 表示视频录制中视频源类型的枚举。
| Name | Value | Description | | 名称 | 值 | 说明 |
| ----------------------------- | ---- | ------------------------------------------------------------ | | ----------------------------- | ---- | ------------------------------- |
| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | The input surface carries raw data.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | 输入surface中携带的是raw data。 |
| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | The input surface carries ES data.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | 输入surface中携带的是ES data。 |
## VideoRecorderProfile<sup>8+</sup> ## VideoRecorderProfile<sup>8+</sup>
Describes the video recording profile. 视频录制的配置文件。
| Name | Type | Mandatory| Description | | 名称 | 参数类型 | 必填 | 说明 |
| ---------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | ---------------- | -------------------------------------------- | ---- | ---------------- |
| audioBitrate | number | Yes | Audio encoding bit rate.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | audioBitrate | number | 是 | 音频编码比特率。 |
| audioChannels | number | Yes | Number of audio channels.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | audioChannels | number | 是 | 音频采集声道数。 |
| audioCodec | [CodecMimeType](#CodecMimeType8) | Yes | Audio encoding format.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | audioCodec | [CodecMimeType](#CodecMimeType8) | 是 | 音频编码格式。 |
| audioSampleRate | number | Yes | Audio sampling rate.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | audioSampleRate | number | 是 | 音频采样率。 |
| fileFormat | [ContainerFormatType](#containerformattype8) | Yes | Container format of a file.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | fileFormat | [ContainerFormatType](#containerformattype8) | 是 | 文件的容器格式。 |
| videoCodec | [CodecMimeType](#CodecMimeType8) | Yes | Video encoding format.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | videoCodec | [CodecMimeType](#CodecMimeType8) | 是 | 视频编码格式。 |
| videoFrameWidth | number | Yes | Width of the recorded video frame.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | videoFrameWidth | number | 是 | 录制视频帧的宽。 |
| videoFrameHeight | number | Yes | Height of the recorded video frame.<br>**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| | videoFrameHeight | number | 是 | 录制视频帧的高。 |
## ContainerFormatType<sup>8+</sup> ## ContainerFormatType<sup>8+</sup>
Enumerates the container format types (CFTs). 表示容器格式类型的枚举,缩写为CFT。
| Name | Value | Description | | 名称 | 值 | 说明 |
| ----------- | ----- | ------------------------------------------------------------ | | ----------- | ----- | --------------------- |
| CFT_MPEG_4 | "mp4" | Video container format MP4.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | CFT_MPEG_4 | "mp4" | 视频的容器格式,MP4。 |
| CFT_MPEG_4A | "m4a" | Audio container format M4A.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | CFT_MPEG_4A | "m4a" | 音频的容器格式,M4A。 |
## Location<sup>8+</sup> ## Location<sup>8+</sup>
Describes the geographical location of the recorded video. 视频录制的地理位置。
| Name | Type| Mandatory| Description | | 名称 | 参数类型 | 必填 | 说明 |
| --------- | -------- | ---- | ------------------------------------------------------------ | | --------- | -------- | ---- | ---------------- |
| latitude | number | Yes | Latitude of the geographical location.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | latitude | number | 是 | 地理位置的纬度。 |
| longitude | number | Yes | Longitude of the geographical location.<br>**System capability**: SystemCapability.Multimedia.Media.Core| | longitude | number | 是 | 地理位置的经度。 |
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册