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

!2098 Done! 1753 媒体文档增加syscaps说明

Merge pull request !2098 from wusongqing/TR1753
......@@ -25,6 +25,9 @@ The full audio playback process includes creating an instance, setting the 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).
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
......@@ -80,7 +83,18 @@ function printfDescription(obj) {
let audioPlayer = media.createAudioPlayer();
SetCallBack(audioPlayer); // Set the event callbacks.
// 2. Set the URI of the audio file.
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback.
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.
// 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.
......@@ -111,6 +125,9 @@ audioPlayer = undefined;
### Normal Playback Scenario
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
......@@ -128,13 +145,27 @@ function SetCallBack(audioPlayer) {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
SetCallBack(audioPlayer); // Set the event callbacks.
/* Set the URI of the audio file selected by the user. */
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback.
/* Set the FD (local playback) of the audio 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.
```
### Switching to the Next Song
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
......@@ -152,16 +183,42 @@ function SetCallBack(audioPlayer) {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
SetCallBack(audioPlayer); // Set the event callbacks.
/* Set the URI of the audio file selected by the user. */
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback.
/* Set the FD (local playback) of the audio 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.
/* Send the instruction to switch to the next song after a period of time. */
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
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
......@@ -179,7 +236,19 @@ function SetCallBack(audioPlayer) {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
SetCallBack(audioPlayer); // Set the event callbacks.
/* Set the URI of the audio file selected by the user. */
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.loop = true; // Set the loop playback attribute.
/* Set the FD (local playback) of the audio 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.
audioPlayer.loop = true; // Set the loop playback attribute.
```
......@@ -23,6 +23,11 @@ For details about the APIs used for audio recording, see [js-apis-media.md](../r
The full audio recording process includes creating an instance, setting recording parameters, starting, pausing, resuming, and stopping recording, and releasing resources.
```js
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
function SetCallBack(audioRecorder) {
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback.
console.log('prepare success');
......@@ -57,6 +62,31 @@ function SetCallBack(audioRecorder) {
});
}
// 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();
// 2. Set the callbacks.
......@@ -68,7 +98,7 @@ let audioRecorderConfig = {
audioSampleRate : 22050,
numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS,
uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', // The file must be created by the caller and granted with proper permissions.
uri : testFdNumber, // testFdNumber is generated by getFd.
location : { latitude : 30, longitude : 130},
}
audioRecorder.prepare(audioRecorderConfig);
......@@ -92,6 +122,11 @@ audioRecorder = undefined;
Unlike the full-process scenario, the normal recording scenario does not include the process of pausing and resuming recording.
```js
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
function SetCallBack(audioPlayer) {
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback.
console.log('prepare success');
......@@ -108,6 +143,32 @@ function SetCallBack(audioPlayer) {
console.log('audio recorder release success');
});
}
// 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();
// 2. Set the callbacks.
......@@ -119,7 +180,7 @@ let audioRecorderConfig = {
audioSampleRate : 22050,
numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS,
uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', // The file must be created by the caller and granted with proper permissions.
uri : testFdNumber, // testFdNumber is generated by getFd.
location : { latitude : 30, longitude : 130},
}
audioRecorder.prepare(audioRecorderConfig)
......
......@@ -28,10 +28,23 @@ For details about the APIs used for video playback, see [js-apis-media.md](../re
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.
For details about the **url** media source input types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_attributes).
For details about how to create an Xcomponent, see [Xcomponent Creation](#Xcomponent).
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
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) {
console.info(`error happened,error Name is ${error.name}`);
......@@ -65,10 +78,19 @@ await media.createVideoPlayer().then((video) => {
}
}, failureCallback).catch(catchCallback);
// Set the URL of the video file selected by the user.
videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4';
// 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.mp4';
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);
});
// Call the Xcomponent interface to obtain the surface ID and save it to the surfaceID variable.
videoPlayer.url = fdPath;
// Set the surface ID to display the video image.
await videoPlayer.setDisplaySurface(surfaceID).then(() => {
......@@ -145,9 +167,18 @@ surfaceID = undefined;
### Normal Playback Scenario
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
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) {
console.info(`error happened,error Name is ${error.name}`);
......@@ -189,10 +220,19 @@ await media.createVideoPlayer().then((video) => {
// Set the event callbacks.
SetCallBack(videoPlayer);
// Set the URL of the video file selected by the user.
videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4';
// 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.mp4';
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);
});
// Call the Xcomponent interface to obtain the surface ID and save it to the surfaceID variable.
videoPlayer.url = fdPath;
// Set the surface ID to display the video image.
await videoPlayer.setDisplaySurface(surfaceID).then(() => {
......@@ -213,9 +253,18 @@ await videoPlayer.play().then(() => {
### Switching to the Next Video Clip
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
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) {
console.info(`error happened,error Name is ${error.name}`);
......@@ -257,10 +306,19 @@ await media.createVideoPlayer().then((video) => {
// Set the event callbacks.
SetCallBack(videoPlayer);
// Set the URL of the video file selected by the user.
videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4';
// 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.mp4';
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);
});
// Call the Xcomponent interface to obtain the surface ID and save it to the surfaceID variable.
videoPlayer.url = fdPath;
// Set the surface ID to display the video image.
await videoPlayer.setDisplaySurface(surfaceID).then(() => {
......@@ -283,7 +341,19 @@ await videoPlayer.reset().then(() => {
console.info('reset success');
}, failureCallback).catch(catchCallback);
videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/next.mp4';
// Set the FD (local playback) of the video file selected by the user.
let fdNextPath = 'fd://'
let nextPath = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/02.mp4';
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(() => {
......@@ -304,9 +374,18 @@ await videoPlayer.play().then(() => {
### Looping a Video Clip
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
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) {
console.info(`error happened,error Name is ${error.name}`);
......@@ -348,10 +427,19 @@ await media.createVideoPlayer().then((video) => {
// Set the event callbacks.
SetCallBack(videoPlayer);
// Set the URL of the video file selected by the user.
videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4';
// 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.mp4';
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);
});
// Call the Xcomponent interface to obtain the surface ID and save it to the surfaceID variable.
videoPlayer.url = fdPath;
// Set the surface ID to display the video image.
await videoPlayer.setDisplaySurface(surfaceID).then(() => {
......@@ -371,3 +459,15 @@ await videoPlayer.play().then(() => {
console.info('play success');
}, failureCallback).catch(catchCallback);
```
### 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>
```
......@@ -23,6 +23,36 @@ For details about the APIs used for video recording, see [js-apis-media.md](../r
The full video recording process includes creating an instance, setting recording parameters, recording video, pausing, resuming, and stopping recording, and releasing resources.
```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 = {
audioBitrate : 48000,
audioChannels : 2,
......@@ -40,7 +70,7 @@ let videoConfig = {
audioSourceType : 1,
videoSourceType : 0,
profile : videoProfile,
url : 'file:///data/media/01.mp4',
url: testFdNumber, // testFdNumber is generated by getFd.
orientationHint : 0,
location : { latitude : 30, longitude : 130 },
}
......@@ -61,6 +91,7 @@ function catchCallback(error) {
let videoRecorder = null; // videoRecorder is an empty object and assigned with a value after createVideoRecorder is successfully called.
let surfaceID = null; // Used to save the surface ID returned by getInputSurface.
// Create a VideoRecorder object.
await media.createVideoRecorder().then((recorder) => {
console.info('case createVideoRecorder called');
......
# 音频播放开发指导
# 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.
**图1** 音频播放状态机
**Figure 1** Playback status
![zh-ch_image_audio_state_machine](figures/zh-ch_image_audio_state_machine.png)
![en-us_image_audio_state_machine](figures/en-us_image_audio_state_machine.png)
**图2** 音频播放零层图
**Figure 2** Layer 0 diagram of audio playback
![zh-ch_image_audio_player](figures/zh-ch_image_audio_player.png)
![en-us_image_audio_player](figures/en-us_image_audio_player.png)
## 开发步骤
## How to Develop
详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md)
For details about the APIs used for audio playback, see [js-apis-media.md](../reference/apis/js-apis-media.md).
### 全流程场景
### Full-Process Scenario
包含流程:创建实例,设置uri,播放音频,跳转播放位置,设置音量,暂停播放,获取轨道信息,停止播放,重置,释放资源等流程。
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.
AudioPlayer支持的src媒体源输入类型可参考:[src属性说明](../reference/apis/js-apis-media.md#audioplayer_属性)
For details about the **src** media source input types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_attributes).
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
//播放界面可切换至已准备好,可点击播放按钮进行播放状态
// The playback page is ready. You can click the Play button to start the playback.
});
audioPlayer.on('play', () => { //设置'play'事件回调
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
//将播放按钮切换至可暂停状态
// The Play button is changed to the pausable state.
});
audioPlayer.on('pause', () => { //设置'pause'事件回调
audioPlayer.on('pause', () => { // Set the 'pause' event callback.
console.info('audio pause success');
//将播放按钮切换至可播放状态
// The Play button is changed to the playable state.
});
audioPlayer.on('stop', () => { //设置'stop'事件回调
audioPlayer.on('stop', () => { // Set the 'stop' event callback.
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', () => { //设置'reset'事件回调
audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio reset success');
//需重新设置src属性后,可继续播放其他音频
// You can reconfigure the src attribute to play another audio file.
});
audioPlayer.on('timeUpdate', (seekDoneTime) => {//设置'timeUpdate'事件回调
audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback.
if (typeof(seekDoneTime) == 'undefined') {
console.info('audio seek fail');
return;
}
console.info('audio seek success, and seek time is ' + seekDoneTime);
//播放进度条更新到seek对应的位置
// The playback progress bar is updated to the seek position.
});
audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调
audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
console.info('audio volumeChange success');
//更新音量显示
// Display the updated volume.
});
audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
});
audioPlayer.on('error', (error) => { //设置'error'事件回调
audioPlayer.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`);
......@@ -79,10 +79,10 @@ function printfDescription(obj) {
}
}
//1、创建实例
// 1. Create an audioPlayer instance.
let audioPlayer = media.createAudioPlayer();
SetCallBack(audioPlayer); //设置事件回调
//2、用户选择音频,设置uri
SetCallBack(audioPlayer); // Set the event callbacks.
// 2. Set the URI of the audio file.
let fdPath = 'fd://'
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
await fileIO.open(path).then(fdNumber) => {
......@@ -94,17 +94,17 @@ await fileIO.open(path).then(fdNumber) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调
//3、播放音频
audioPlayer.play(); //需等待'dataLoad'事件回调完成后,才可调用play进行播放,触发'play'事件回调
//4、跳转播放位置
audioPlayer.seek(30000); //触发'timeUpdate'事件回调,seek到30000ms处播放
//5、设置音量
audioPlayer.setVolume(0.5); //触发'volumeChange'事件回调
//6、暂停播放
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') {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
......@@ -113,39 +113,39 @@ audioPlayer.getTrackDescription((error, arrlist) => { //通过回调方式获
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
});
//8、停止播放
audioPlayer.stop(); //触发'stop'事件回调
//9、重置播放资源
audioPlayer.reset(); //触发'reset'事件回调后,重新设置src属性,可完成切歌
//10、释放资源
audioPlayer.release(); //audioPlayer资源被销毁
// 8. Stop playback.
audioPlayer.stop(); // Trigger the 'stop' event callback.
// 9. Reset the playback resources.
audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
// 10. Release the resource.
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
```
### 正常播放场景
### Normal Playback Scenario
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { //设置'play'事件回调
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
});
audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
SetCallBack(audioPlayer); //设置事件回调
/* 用户选择视频设置fd(本地播放) */
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
SetCallBack(audioPlayer); // Set the event callbacks.
/* Set the FD (local playback) of the audio 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) => {
......@@ -157,33 +157,33 @@ await fileIO.open(path).then(fdNumber) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
```
### 切歌场景
### Switching to the Next Song
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { //设置'play'事件回调
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
});
audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
SetCallBack(audioPlayer); //设置事件回调
/* 用户选择视频设置fd(本地播放) */
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
SetCallBack(audioPlayer); // Set the event callbacks.
/* Set the FD (local playback) of the audio 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) => {
......@@ -195,11 +195,11 @@ await fileIO.open(path).then(fdNumber) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调
/* 播放一段时间后,下发切歌指令 */
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();
/* 用户选择视频设置fd(本地播放) */
/* 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) => {
......@@ -213,31 +213,31 @@ await fileIO.open(nextPath).then(fdNumber) => {
audioPlayer.src = fdNextPath;
```
### 单曲循环场景
### Looping a Song
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { //设置'play'事件回调
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
});
audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
SetCallBack(audioPlayer); //设置事件回调
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
SetCallBack(audioPlayer); // Set the event callbacks.
/* 用户选择视频设置fd(本地播放) */
/* Set the FD (local playback) of the audio 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) => {
......@@ -249,6 +249,6 @@ await fileIO.open(path).then(fdNumber) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调
audioPlayer.loop = true; //设置循环播放属性
```
\ No newline at end of file
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.loop = true; // Set the loop playback attribute.
```
# 音频录制开发指导
## 场景介绍
音频录制的主要工作是捕获音频信号,完成音频编码并保存到文件中,帮助开发者轻松实现音频录制功能。它允许调用者指定音频录制的采样率、声道数、编码格式、封装格式、文件路径等参数。
**图1** 音频录制状态机
![zh-ch_image_audio_recorder_state_machine](figures/zh-ch_image_audio_recorder_state_machine.png)
**图2** 音频录制零层图
![zh-ch_image_audio_recorder_zero](figures/zh-ch_image_audio_recorder_zero.png)
## 开发步骤
详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md)
### 全流程场景
包含流程:创建实例,设置录制参数,录制音频,暂停录制,恢复录制,停止录制,释放资源等流程。
```js
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
function SetCallBack(audioRecorder) {
audioRecorder.on('prepare', () => { // 设置'prepare'事件回调
console.log('prepare success');
// 录制界面可切换至已准备好,可点击录制按钮进行录制
});
audioRecorder.on('start', () => { // 设置'start'事件回调
console.log('audio recorder start success');
// 将录制按钮切换至可暂停状态
});
audioRecorder.on('pause', () => { // 设置'pause'事件回调
console.log('audio recorder pause success');
// 将录制按钮切换至可录制状态
});
audioRecorder.on('resume', () => { // 设置'resume'事件回调
console.log('audio recorder resume success');
// 将录制按钮切换至可暂停状态
});
audioRecorder.on('stop', () => { // 设置'stop'事件回调
console.log('audio recorder stop success');
});
audioRecorder.on('release', () => { // 设置'release'事件回调
console.log('audio recorder release success');
});
audioRecorder.on('reset', () => { // 设置'reset'事件回调
console.log('audio recorder reset success');
// 需要重新设置录制参数才能再次录制
});
audioRecorder.on('error', (error) => { // 设置'error'事件回调
console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`);
});
}
// pathName是传入的录制文件名,例如:01.mp3,生成后的文件地址:/storage/media/100/local/files/Movies/01.mp3
// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、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.创建实例
let audioRecorder = media.createAudioRecorder();
// 2.设置回调
SetCallBack(audioRecorder);
// 3.设置录制参数
let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC ,
audioEncodeBitRate : 22050,
audioSampleRate : 22050,
numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS,
uri : testFdNumber, // testFdNumber由getFd生成
location : { latitude : 30, longitude : 130},
}
audioRecorder.prepare(audioRecorderConfig);
// 4.开始录制
audioRecorder.start(); // 需等待'prepare'事件回调完成后,才可调用start进行录制,触发'start'事件回调
// 5.暂停录制
audioRecorder.pause(); // 需等待'start'事件回调完成后,才可调用pause进行暂停,触发'pause'事件回调
// 6.恢复录制
audioRecorder.resume(); // 需等待'pause'事件回调完成后,才可调用resume进行录制,触发'resume'事件回调
// 7.停止录制
audioRecorder.stop(); // 需等待'start'或'resume'事件回调完成后,才可调用stop进行暂停,触发'stop'事件回调
// 8.重置录制
audioRecorder.reset(); // 触发'reset'事件回调后,重新进行prepare,才可重新录制
// 9.释放资源
audioRecorder.release(); // audioRecorder资源被销毁
audioRecorder = undefined;
```
### 正常录制场景
与全流程场景不同,不包括暂停录制,恢复录制的过程。
```js
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
function SetCallBack(audioPlayer) {
audioRecorder.on('prepare', () => { // 设置'prepare'事件回调
console.log('prepare success');
// 录制界面可切换至已准备好,可点击录制按钮进行录制
});
audioRecorder.on('start', () => { // 设置'start'事件回调
console.log('audio recorder start success');
// 将录制按钮切换至可暂停状态
});
audioRecorder.on('stop', () => { // 设置'stop'事件回调
console.log('audio recorder stop success');
});
audioRecorder.on('release', () => { // 设置'release'事件回调
console.log('audio recorder release success');
});
}
// pathName是传入的录制文件名,例如:01.mp3,生成后的文件地址:/storage/media/100/local/files/Movies/01.mp3
// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、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.创建实例
let audioRecorder = media.createAudioRecorder();
// 2.设置回调
SetCallBack(audioRecorder);
// 3.设置录制参数
let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC ,
audioEncodeBitRate : 22050,
audioSampleRate : 22050,
numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS,
uri : testFdNumber, // testFdNumber由getFd生成
location : { latitude : 30, longitude : 130},
}
audioRecorder.prepare(audioRecorderConfig)
// 4.开始录制
audioRecorder.start(); // 需等待'prepare'事件回调完成后,才可调用start进行录制,触发'start'事件回调
// 5.停止录制
audioRecorder.stop(); // 需等待'start'或'resume'事件回调完成后,才可调用stop进行暂停,触发'stop'事件回调
// 6.释放资源
audioRecorder.release(); // audioRecorder资源被销毁
audioRecorder = undefined;
```
# 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
![en-us_image_audio_recorder_state_machine](figures/en-us_image_audio_recorder_state_machine.png)
**Figure 2** Layer 0 diagram of audio recording
![en-us_image_audio_recorder_zero](figures/en-us_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).
### 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
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
function SetCallBack(audioRecorder) {
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback.
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.
console.log('audio recorder start success');
// The Record button is changed to the pausable state.
});
audioRecorder.on('pause', () => { // Set the 'pause' event callback.
console.log('audio recorder pause success');
// The Record button is changed to the recordable state.
});
audioRecorder.on('resume', () => { // Set the 'resume' event callback.
console.log('audio recorder resume success');
// The Record button is changed to the pausable state.
});
audioRecorder.on('stop', () => { // Set the 'stop' event callback.
console.log('audio recorder stop success');
});
audioRecorder.on('release', () => { // Set the 'release' event callback.
console.log('audio recorder release success');
});
audioRecorder.on('reset', () => { // Set the 'reset' event callback.
console.log('audio recorder reset success');
// You need to reset the recording parameters for another recording.
});
audioRecorder.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`);
});
}
// 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();
// 2. Set the callbacks.
SetCallBack(audioRecorder);
// 3. Set the recording parameters.
let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC ,
audioEncodeBitRate : 22050,
audioSampleRate : 22050,
numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS,
uri : testFdNumber, // testFdNumber is generated by getFd.
location : { latitude : 30, longitude : 130},
}
audioRecorder.prepare(audioRecorderConfig);
// 4. Start recording.
audioRecorder.start(); // The start method can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete.
// 5. Pause recording.
audioRecorder.pause(); // The pause method can be called to trigger the 'pause' event callback only after the 'start' event callback is complete.
// 6. Resume recording.
audioRecorder.resume(); // The resume method can be called to trigger the 'resume' event callback only after the 'pause' event callback is complete.
// 7. Stop recording.
audioRecorder.stop(); // The stop method can be called to trigger the 'stop' event callback only after the 'start' or 'resume' event callback is complete.
// 8. Reset recording.
audioRecorder.reset(); // The prepare method can be called for another recording only after the 'reset' event callback is complete.
// 9. Release resources.
audioRecorder.release(); // The AudioRecorder resource is destroyed.
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
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
function SetCallBack(audioPlayer) {
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback.
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.
console.log('audio recorder start success');
// The Record button is changed to the pausable state.
});
audioRecorder.on('stop', () => { // Set the 'stop' event callback.
console.log('audio recorder stop success');
});
audioRecorder.on('release', () => { // Set the 'release' event callback.
console.log('audio recorder release success');
});
}
// 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();
// 2. Set the callbacks.
SetCallBack(audioRecorder);
// 3. Set the recording parameters.
let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC ,
audioEncodeBitRate : 22050,
audioSampleRate : 22050,
numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS,
uri : testFdNumber, // testFdNumber is generated by getFd.
location : { latitude : 30, longitude : 130},
}
audioRecorder.prepare(audioRecorderConfig)
// 4. Start recording.
audioRecorder.start(); // The start method can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete.
// 5. Stop recording.
audioRecorder.stop(); // The stop method can be called to trigger the 'stop' event callback only after the 'start' or 'resume' event callback is complete.
// 6. Release resources.
audioRecorder.release(); // The AudioRecorder resource is destroyed.
audioRecorder = undefined;
```
# 视频录制开发指导
## 场景介绍
视频录制的主要工作是捕获音视频信号,完成音视频编码并保存到文件中,帮助开发者轻松实现音视频录制功能。它允许调用者指定录制的编码格式、封装格式、文件路径等参数。
**图1** 视频录制状态机
![zh-ch_image_video_recorder_state_machine](figures/zh-ch_image_video_recorder_state_machine.png)
**图2** 视频录制零层图
![zh-ch_image_video_recorder_zero](figures/zh-ch_image_video_recorder_zero.png)
## 开发步骤
详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md)
### 全流程场景
包含流程:创建实例,设置录制参数,录制视频,暂停录制,恢复录制,停止录制,释放资源等流程。
```js
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
// pathName是传入的录制文件名,例如:01.mp4,生成后的文件地址:/storage/media/100/local/files/Movies/01.mp4
// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、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 = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000,
fileFormat : 'mp4',
videoBitrate : 48000,
videoCodec : 'video/mp4v-es',
videoFrameWidth : 640,
videoFrameHeight : 480,
videoFrameRate : 30
}
let videoConfig = {
audioSourceType : 1,
videoSourceType : 0,
profile : videoProfile,
url : testFdNumber, // testFdNumber由getFd生成
orientationHint : 0,
location : { latitude : 30, longitude : 130 },
}
// 当发生错误上上报的错误回调接口
function failureCallback(error) {
console.info('error happened, error name is ' + error.name);
console.info('error happened, error code is ' + error.code);
console.info('error happened, error message is ' + error.message);
}
// 当发生异常时,系统调用的错误回调接口
function catchCallback(error) {
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 message is ' + error.message);
}
let videoRecorder = null; // videoRecorder空对象在createVideoRecorder成功后赋值
let surfaceID = null; // 用于保存getInputSurface返回的surfaceID
// 创建videoRecorder对象
await media.createVideoRecorder().then((recorder) => {
console.info('case createVideoRecorder called');
if (typeof (recorder) != 'undefined') {
videoRecorder = recorder;
console.info('createVideoRecorder success');
} else {
console.info('createVideoRecorder failed');
}
}, failureCallback).catch(catchCallback);
// 获取surfaceID并保存下来传递给camera相关接口
await videoRecorder.getInputSurface().then((surface) => {
console.info('getInputSurface success');
surfaceID = surface;
}, failureCallback).catch(catchCallback);
// 视频录制依赖相机相关接口,以下需要先调用相机起流接口后才能继续执行
// 视频录制启动接口
await videoRecorder.start().then(() => {
console.info('start success');
}, failureCallback).catch(catchCallback);
// 调用pause接口时需要暂停camera出流
await videoRecorder.pause().then(() => {
console.info('pause success');
}, failureCallback).catch(catchCallback);
// 调用resume接口时需要恢复camera出流
await videoRecorder.resume().then(() => {
console.info('resume success');
}, failureCallback).catch(catchCallback);
// 停止camera出流后,停止视频录制
await videoRecorder.stop().then(() => {
console.info('stop success');
}, failureCallback).catch(catchCallback);
// 重置录制相关配置
await videoRecorder.reset().then(() => {
console.info('reset success');
}, failureCallback).catch(catchCallback);
// 释放视频录制相关资源并释放camera对象相关资源
await videoRecorder.release().then(() => {
console.info('release success');
}, failureCallback).catch(catchCallback);
// 相关对象置null
videoRecorder = null;
surfaceID = null;
```
# 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
![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png)
**Figure 2** Layer 0 diagram of video recording
![en-us_image_video_recorder_zero](figures/en-us_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).
### 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
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 = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000,
fileFormat : 'mp4',
videoBitrate : 48000,
videoCodec : 'video/mp4v-es',
videoFrameWidth : 640,
videoFrameHeight : 480,
videoFrameRate : 30
}
let videoConfig = {
audioSourceType : 1,
videoSourceType : 0,
profile : videoProfile,
url: testFdNumber, // testFdNumber is generated by getFd.
orientationHint : 0,
location : { latitude : 30, longitude : 130 },
}
// Error callback triggered in the case of an error
function failureCallback(error) {
console.info('error happened, error name is ' + error.name);
console.info('error happened, error code is ' + error.code);
console.info('error happened, error message is ' + error.message);
}
// Error callback triggered in the case of an exception
function catchCallback(error) {
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 message is ' + error.message);
}
let videoRecorder = null; // videoRecorder is an empty object and assigned with a value after createVideoRecorder is successfully called.
let surfaceID = null; // Used to save the surface ID returned by getInputSurface.
// Create a VideoRecorder object.
await media.createVideoRecorder().then((recorder) => {
console.info('case createVideoRecorder called');
if (typeof (recorder) != 'undefined') {
videoRecorder = recorder;
console.info('createVideoRecorder success');
} else {
console.info('createVideoRecorder failed');
}
}, failureCallback).catch(catchCallback);
// Obtain the surface ID, save it, and pass it to camera-related interfaces.
await videoRecorder.getInputSurface().then((surface) => {
console.info('getInputSurface success');
surfaceID = surface;
}, 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(() => {
console.info('start success');
}, failureCallback).catch(catchCallback);
// Pause video playback before the video output stop interface is invoked.
await videoRecorder.pause().then(() => {
console.info('pause success');
}, failureCallback).catch(catchCallback);
// Resume video playback after the video output start interface is invoked.
await videoRecorder.resume().then(() => {
console.info('resume success');
}, failureCallback).catch(catchCallback);
// Stop video recording after the video output stop interface is invoked.
await videoRecorder.stop().then(() => {
console.info('stop success');
}, failureCallback).catch(catchCallback);
// Reset the recording configuration.
await videoRecorder.reset().then(() => {
console.info('reset success');
}, failureCallback).catch(catchCallback);
// Release the video recording resources and camera object resources.
await videoRecorder.release().then(() => {
console.info('release success');
}, failureCallback).catch(catchCallback);
// Set the related object to null.
videoRecorder = null;
surfaceID = null;
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册