未验证 提交 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 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;
``` ```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册