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

!3383 音频播放demo修改

Merge pull request !3383 from hwgaizw/ziliao
...@@ -28,26 +28,37 @@ AudioPlayer支持的src媒体源输入类型可参考:[src属性说明](../ref ...@@ -28,26 +28,37 @@ AudioPlayer支持的src媒体源输入类型可参考:[src属性说明](../ref
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) { //打印码流轨道信息
function printfDescription(obj) {
for (let item in obj) {
let property = obj[item];
console.info('audio key is ' + item);
console.info('audio value is ' + property);
}
}
//设置播放器回调函数
function setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
console.info('audio set source success'); console.info('audio set source success');
//播放界面可切换至已准备好,可点击播放按钮进行播放状态 audioPlayer.play(); //需等待'dataLoad'事件回调完成后,才可调用play进行播放,触发'play'事件回调
}); });
audioPlayer.on('play', () => { //设置'play'事件回调 audioPlayer.on('play', () => { //设置'play'事件回调
console.info('audio play success'); console.info('audio play success');
//将播放按钮切换至可暂停状态 audioPlayer.pause(); //触发'pause'事件回调,暂停播放
}); });
audioPlayer.on('pause', () => { //设置'pause'事件回调 audioPlayer.on('pause', () => { //设置'pause'事件回调
console.info('audio pause success'); console.info('audio pause success');
//将播放按钮切换至可播放状态 audioPlayer.seek(5000); //触发'timeUpdate'事件回调,seek到5000ms处播放
}); });
audioPlayer.on('stop', () => { //设置'stop'事件回调 audioPlayer.on('stop', () => { //设置'stop'事件回调
console.info('audio stop success'); console.info('audio stop success');
//播放停止,播放进度条归零,播放按钮切换至可播放状态 audioPlayer.reset(); //触发'reset'事件回调后,重新设置src属性,可完成切歌
}); });
audioPlayer.on('reset', () => { //设置'reset'事件回调 audioPlayer.on('reset', () => { //设置'reset'事件回调
console.info('audio reset success'); console.info('audio reset success');
//需重新设置src属性后,可继续播放其他音频 audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer = undefined;
}); });
audioPlayer.on('timeUpdate', (seekDoneTime) => {//设置'timeUpdate'事件回调 audioPlayer.on('timeUpdate', (seekDoneTime) => {//设置'timeUpdate'事件回调
if (typeof(seekDoneTime) == 'undefined') { if (typeof(seekDoneTime) == 'undefined') {
...@@ -55,11 +66,20 @@ function SetCallBack(audioPlayer) { ...@@ -55,11 +66,20 @@ function SetCallBack(audioPlayer) {
return; return;
} }
console.info('audio seek success, and seek time is ' + seekDoneTime); console.info('audio seek success, and seek time is ' + seekDoneTime);
//播放进度条更新到seek对应的位置 audioPlayer.setVolume(0.5); //触发'volumeChange'事件回调
}); });
audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调 audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调
console.info('audio volumeChange success'); console.info('audio volumeChange success');
//更新音量显示 audioPlayer.getTrackDescription((error, arrlist) => { //通过回调方式获取音频轨道信息
if (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
}
} else {
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
audioPlayer.stop(); //触发'stop'事件回调,停止播放
});
}); });
audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发 audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发
console.info('audio play finish'); console.info('audio play finish');
...@@ -71,56 +91,24 @@ function SetCallBack(audioPlayer) { ...@@ -71,56 +91,24 @@ function SetCallBack(audioPlayer) {
}); });
} }
function printfDescription(obj) { async function audioPlayerDemo() {
for (let item in obj) { // 1. 创建实例
let property = obj[item]; let audioPlayer = media.createAudioPlayer();
console.info('audio key is ' + item); setCallBack(audioPlayer); //设置事件回调
console.info('audio value is ' + property); //2. 用户选择音频,设置uri
} let fdPath = 'fd://'
} // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" 命令,将其推送到设备上
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
//1. 创建实例 await fileIO.open(path).then((fdNumber) => {
let audioPlayer = media.createAudioPlayer();
SetCallBack(audioPlayer); //设置事件回调
//2. 用户选择音频,设置uri
let fdPath = 'fd://'
// path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" 命令,将其推送到设备上
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
await fileIO.open(path).then(fdNumber) => {
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath); console.info('open fd sucess fd is' + fdPath);
}, (err) => { }, (err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}),catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调
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) => { //通过回调方式获取音频轨道信息
if (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
}
} else {
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
});
//8. 停止播放
audioPlayer.stop(); //触发'stop'事件回调
//9. 重置播放资源
audioPlayer.reset(); //触发'reset'事件回调后,重新设置src属性,可完成切歌
//10. 释放资源
audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer = undefined;
``` ```
### 正常播放场景 ### 正常播放场景
...@@ -128,8 +116,9 @@ audioPlayer = undefined; ...@@ -128,8 +116,9 @@ audioPlayer = undefined;
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fileIO from '@ohos.fileio'
export class AudioDemo {
function SetCallBack(audioPlayer) { // 设置播放器回调函数
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调 audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调
...@@ -142,24 +131,25 @@ function SetCallBack(audioPlayer) { ...@@ -142,24 +131,25 @@ function SetCallBack(audioPlayer) {
audioPlayer.release(); //audioPlayer资源被销毁 audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer = undefined; audioPlayer = undefined;
}); });
} }
let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例 async audioPlayerDemo() {
SetCallBack(audioPlayer); //设置事件回调 let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
/* 用户选择音频设置fd(本地播放) */ this.setCallBack(audioPlayer); //设置事件回调
let fdPath = 'fd://' let fdPath = 'fd://'
// path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" 命令,将其推送到设备上 // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" 命令,将其推送到设备上
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
await fileIO.open(path).then(fdNumber) => { await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath); console.info('open fd sucess fd is' + fdPath);
}, (err) => { }, (err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}),catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调
audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 }
}
``` ```
### 切歌场景 ### 切歌场景
...@@ -167,54 +157,62 @@ audioPlayer.src = fdPath; //设置src属性,并触 ...@@ -167,54 +157,62 @@ audioPlayer.src = fdPath; //设置src属性,并触
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fileIO from '@ohos.fileio'
export class AudioDemo {
function SetCallBack(audioPlayer) { // 设置播放器回调函数
private isNextMusic = false;
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调 audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调
}); });
audioPlayer.on('play', () => { //设置'play'事件回调 audioPlayer.on('play', () => { //设置'play'事件回调
console.info('audio play success'); console.info('audio play success');
audioPlayer.reset(); //调用reset方法,出发'reset'事件回调
}); });
audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发 audioPlayer.on('reset', () => { //设置'reset'事件回调
console.info('audio play finish'); console.info('audio play success');
if (!this.isNextMusic) { //当isNextMusic 为false时,实现切歌功能
this.nextMusic(audioPlayer); //实现切歌功能
} else {
audioPlayer.release(); //audioPlayer资源被销毁 audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer = undefined; audioPlayer = undefined;
}
}); });
} }
let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例 async nextMusic(audioPlayer) {
SetCallBack(audioPlayer); //设置事件回调 this.isNextMusic = true;
/* 用户选择音频设置fd(本地播放) */ let nextFdPath = 'fd://'
let fdPath = 'fd://' // path路径的码流可通过"hdc file send D:\xxx\02.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" 命令,将其推送到设备上
// path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" 命令,将其推送到设备上 let nextpath = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/02.mp3';
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; await fileIO.open(nextpath).then((fdNumber) => {
await fileIO.open(path).then(fdNumber) => { nextFdPath = nextFdPath + '' + fdNumber;
fdPath = fdPath + '' + fdNumber; console.info('open fd sucess fd is' + nextFdPath);
console.info('open fd sucess fd is' + fdPath); }, (err) => {
}, (err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}),catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = nextFdPath; //设置src属性,并重新触发触发'dataLoad'事件回调
audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 }
/* 播放一段时间后,下发切歌指令 */
audioPlayer.reset();
/* 用户选择音频设置fd(本地播放) */ async audioPlayerDemo() {
let fdNextPath = 'fd://' let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
// path路径的码流可通过"hdc file send D:\xxx\02.mp3 /data/accounts/account_0/appdata" 命令,将其推送到设备上 this.setCallBack(audioPlayer); //设置事件回调
let nextPath = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/02.mp3'; let fdPath = 'fd://'
await fileIO.open(nextPath).then(fdNumber) => { // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" 命令,将其推送到设备上
fdNextPath = fdNextPath + '' + fdNumber; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
console.info('open fd sucess fd is' + fdNextPath); await fileIO.open(path).then((fdNumber) => {
}, (err) => { fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}),catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdNextPath; audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调
}
}
``` ```
### 单曲循环场景 ### 单曲循环场景
...@@ -222,40 +220,36 @@ audioPlayer.src = fdNextPath; ...@@ -222,40 +220,36 @@ audioPlayer.src = fdNextPath;
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fileIO from '@ohos.fileio'
export class AudioDemo {
function SetCallBack(audioPlayer) { // 设置播放器回调函数
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.loop = true; //设置循环播放属性
audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调 audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调
}); });
audioPlayer.on('play', () => { //设置'play'事件回调 audioPlayer.on('play', () => { //设置'play'事件回调,开始循环播放
console.info('audio play success'); console.info('audio play success');
}); });
audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发 }
console.info('audio play finish');
audioPlayer.release(); //audioPlayer资源被销毁
audioPlayer = undefined;
});
}
let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
SetCallBack(audioPlayer); //设置事件回调
/* 用户选择音频设置fd(本地播放) */ async audioPlayerDemo() {
let fdPath = 'fd://' let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
// path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" 命令,将其推送到设备上 this.setCallBack(audioPlayer); //设置事件回调
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; let fdPath = 'fd://'
await fileIO.open(path).then(fdNumber) => { // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" 命令,将其推送到设备上
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath); console.info('open fd sucess fd is' + fdPath);
}, (err) => { }, (err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}),catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调
audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 }
audioPlayer.loop = true; //设置循环播放属性 }
``` ```
## 相关实例 ## 相关实例
...@@ -263,7 +257,6 @@ audioPlayer.loop = true; //设置循环播放属性 ...@@ -263,7 +257,6 @@ audioPlayer.loop = true; //设置循环播放属性
针对音频播放开发,有以下相关实例可供参考: 针对音频播放开发,有以下相关实例可供参考:
- [`JsDistributedMusicPlayer`:分布式音乐播放(JS)(API7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer) - [`JsDistributedMusicPlayer`:分布式音乐播放(JS)(API7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer)
- [`JsAudioPlayer`:音频播放和管理(JS)(API7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer) - [`JsAudioPlayer`:音频播放和管理(JS)(API7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer)
- [`eTsAudioPlayer`: 音频播放器(eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [音频播放器](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) - [音频播放器](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
\ No newline at end of file
...@@ -25,46 +25,49 @@ ...@@ -25,46 +25,49 @@
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary' import mediaLibrary from '@ohos.multimedia.mediaLibrary'
export class AudioRecorderDemo {
private testFdNumber; // 用于保存fd地址
let testFdNumber; // 设置音频录制相关回调函数
setCallBack(audioRecorder) {
function SetCallBack(audioRecorder) {
audioRecorder.on('prepare', () => { // 设置'prepare'事件回调 audioRecorder.on('prepare', () => { // 设置'prepare'事件回调
console.log('prepare success'); console.log('prepare success');
// 录制界面可切换至已准备好,可点击录制按钮进行录制 audioRecorder.start(); // 调用start方法开始录制,并触发start回调
}); });
audioRecorder.on('start', () => { // 设置'start'事件回调 audioRecorder.on('start', () => { // 设置'start'事件回调
console.log('audio recorder start success'); console.log('audio recorder start success');
// 将录制按钮切换至可暂停状态 audioRecorder.pause(); // 调用pause方法暂停录制,并触发pause回调
}); });
audioRecorder.on('pause', () => { // 设置'pause'事件回调 audioRecorder.on('pause', () => { // 设置'pause'事件回调
console.log('audio recorder pause success'); console.log('audio recorder pause success');
// 将录制按钮切换至可录制状态 audioRecorder.resume(); // 调用resume方法恢复录制,并触发resume回调
}); });
audioRecorder.on('resume', () => { // 设置'resume'事件回调 audioRecorder.on('resume', () => { // 设置'resume'事件回调
console.log('audio recorder resume success'); console.log('audio recorder resume success');
// 将录制按钮切换至可暂停状态 audioRecorder.stop(); // 调用stop方法停止录制,并触发stop回调
}); });
audioRecorder.on('stop', () => { // 设置'stop'事件回调 audioRecorder.on('stop', () => { // 设置'stop'事件回调
console.log('audio recorder stop success'); console.log('audio recorder stop success');
}); audioRecorder.reset(); // 调用reset方法重置录制,并触发reset回调
audioRecorder.on('release', () => { // 设置'release'事件回调
console.log('audio recorder release success');
}); });
audioRecorder.on('reset', () => { // 设置'reset'事件回调 audioRecorder.on('reset', () => { // 设置'reset'事件回调
console.log('audio recorder reset success'); console.log('audio recorder reset success');
// 需要重新设置录制参数才能再次录制 audioRecorder.release(); // 调用release方法,释放资源,并触发release回调
});
audioRecorder.on('release', () => { // 设置'release'事件回调
console.log('audio recorder release success');
audioRecorder = undefined;
}); });
audioRecorder.on('error', (error) => { // 设置'error'事件回调 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是传入的录制文件名,例如:01.mp3,生成后的文件地址:/storage/media/100/local/files/Movies/01.mp3 // pathName是传入的录制文件名,例如:01.mp3,生成后的文件地址:/storage/media/100/local/files/Video/01.mp3
// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA // 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA
async function getFd(pathName) { async getFd(pathName) {
let displayName = pathName; let displayName = pathName;
const mediaTest = mediaLibrary.getMediaLibrary(); const mediaTest = mediaLibrary.getMediaLibrary();
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
...@@ -80,41 +83,29 @@ async function getFd(pathName) { ...@@ -80,41 +83,29 @@ async function getFd(pathName) {
let fetchFileResult = await mediaTest.getFileAssets(fetchOp); let fetchFileResult = await mediaTest.getFileAssets(fetchOp);
let fileAsset = await fetchFileResult.getAllObject(); let fileAsset = await fetchFileResult.getAllObject();
let fdNumber = await fileAsset[0].open('Rw'); let fdNumber = await fileAsset[0].open('Rw');
fdNumber = "fd://" + fdNumber.toString(); this.testFdNumber = "fd://" + fdNumber.toString();
testFdNumber = fdNumber; }
} }
}
await getFd('01.mp3');
// 1.创建实例 async audioRecorderDemo() {
let audioRecorder = media.createAudioRecorder(); // 1.创建实例
// 2.设置回调 let audioRecorder = media.createAudioRecorder();
SetCallBack(audioRecorder); // 2.设置回调
// 3.设置录制参数 this.setCallBack(audioRecorder);
let audioRecorderConfig = { await this.getFd('01.mp3'); // 调用getFd方法获取需要录制文件的fd地址
audioEncoder : media.AudioEncoder.AAC_LC , // 3.设置录制参数
let audioRecorderConfig = {
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS, uri : this.testFdNumber, // testFdNumber由getFd生成
uri : testFdNumber, // testFdNumber由getFd生成
location : { latitude : 30, longitude : 130}, location : { latitude : 30, longitude : 130},
audioEncoderMime : media.CodecMimeType.AUDIO_AAC,
fileFormat : media.ContainerFormatType.CFT_MPEG_4A,
}
audioRecorder.prepare(audioRecorderConfig); // 调用prepare方法,触发prepare回调函数
}
} }
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;
``` ```
### 正常录制场景 ### 正常录制场景
...@@ -124,29 +115,37 @@ audioRecorder = undefined; ...@@ -124,29 +115,37 @@ audioRecorder = undefined;
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary' import mediaLibrary from '@ohos.multimedia.mediaLibrary'
export class AudioRecorderDemo {
private testFdNumber; // 用于保存fd地址
let testFdNumber; // 设置音频录制相关回调函数
setCallBack(audioRecorder) {
function SetCallBack(audioRecorder) {
audioRecorder.on('prepare', () => { // 设置'prepare'事件回调 audioRecorder.on('prepare', () => { // 设置'prepare'事件回调
console.log('prepare success'); console.log('prepare success');
// 录制界面可切换至已准备好,可点击录制按钮进行录制 audioRecorder.start(); // 调用start方法开始录制,并触发start回调
}); });
audioRecorder.on('start', () => { // 设置'start'事件回调 audioRecorder.on('start', () => { // 设置'start'事件回调
console.log('audio recorder start success'); console.log('audio recorder start success');
// 将录制按钮切换至可暂停状态 audioRecorder.stop(); // 调用stop方法停止录制,并触发stop回调
}); });
audioRecorder.on('stop', () => { // 设置'stop'事件回调 audioRecorder.on('stop', () => { // 设置'stop'事件回调
console.log('audio recorder stop success'); console.log('audio recorder stop success');
audioRecorder.release(); // 调用release方法,释放资源,并触发release回调
}); });
audioRecorder.on('release', () => { // 设置'release'事件回调 audioRecorder.on('release', () => { // 设置'release'事件回调
console.log('audio recorder release success'); console.log('audio recorder release success');
audioRecorder = undefined;
}); });
} 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 // pathName是传入的录制文件名,例如:01.mp3,生成后的文件地址:/storage/media/100/local/files/Video/01.mp3
// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA // 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA
async function getFd(pathName) { async getFd(pathName) {
let displayName = pathName; let displayName = pathName;
const mediaTest = mediaLibrary.getMediaLibrary(); const mediaTest = mediaLibrary.getMediaLibrary();
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
...@@ -162,35 +161,29 @@ async function getFd(pathName) { ...@@ -162,35 +161,29 @@ async function getFd(pathName) {
let fetchFileResult = await mediaTest.getFileAssets(fetchOp); let fetchFileResult = await mediaTest.getFileAssets(fetchOp);
let fileAsset = await fetchFileResult.getAllObject(); let fileAsset = await fetchFileResult.getAllObject();
let fdNumber = await fileAsset[0].open('Rw'); let fdNumber = await fileAsset[0].open('Rw');
fdNumber = "fd://" + fdNumber.toString(); this.testFdNumber = "fd://" + fdNumber.toString();
testFdNumber = fdNumber; }
} }
}
await getFd('01.mp3');
// 1.创建实例 async audioRecorderDemo() {
let audioRecorder = media.createAudioRecorder(); // 1.创建实例
// 2.设置回调 let audioRecorder = media.createAudioRecorder();
SetCallBack(audioRecorder); // 2.设置回调
// 3.设置录制参数 this.setCallBack(audioRecorder);
let audioRecorderConfig = { await this.getFd('01.mp3'); // 调用getFd方法获取需要录制文件的fd地址
audioEncoder : media.AudioEncoder.AAC_LC , // 3.设置录制参数
let audioRecorderConfig = {
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS, uri : this.testFdNumber, // testFdNumber由getFd生成
uri : testFdNumber, // testFdNumber由getFd生成
location : { latitude : 30, longitude : 130}, location : { latitude : 30, longitude : 130},
audioEncoderMime : media.CodecMimeType.AUDIO_AAC,
fileFormat : media.ContainerFormatType.CFT_MPEG_4A,
}
audioRecorder.prepare(audioRecorderConfig); // 调用prepare方法,触发prepare回调函数
}
} }
audioRecorder.prepare(audioRecorderConfig)
// 4.开始录制
audioRecorder.start(); // 需等待'prepare'事件回调完成后,才可调用start进行录制,触发'start'事件回调
// 5.停止录制
audioRecorder.stop(); // 需等待'start'或'resume'事件回调完成后,才可调用stop进行暂停,触发'stop'事件回调
// 6.释放资源
audioRecorder.release(); // audioRecorder资源被销毁
audioRecorder = undefined;
``` ```
## 相关实例 ## 相关实例
...@@ -198,5 +191,5 @@ audioRecorder = undefined; ...@@ -198,5 +191,5 @@ audioRecorder = undefined;
针对音频录制开发,有以下相关实例可供参考: 针对音频录制开发,有以下相关实例可供参考:
- [`Recorder`:录音机(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder) - [`Recorder`:录音机(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)
- [`eTsAudioPlayer`: 音频播放器(eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [音频播放器](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) - [音频播放器](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -25,12 +25,11 @@ ...@@ -25,12 +25,11 @@
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary' import mediaLibrary from '@ohos.multimedia.mediaLibrary'
export class VideoRecorderDemo {
let testFdNumber; private testFdNumber; // 用于保存fd地址
// pathName是传入的录制文件名,例如:01.mp3,生成后的文件地址:/storage/media/100/local/files/Video/01.mp4
// pathName是传入的录制文件名,例如:01.mp4,生成后的文件地址:/storage/media/100/local/files/Movies/01.mp4 // 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA
// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA async getFd(pathName) {
async function getFd(pathName) {
let displayName = pathName; let displayName = pathName;
const mediaTest = mediaLibrary.getMediaLibrary(); const mediaTest = mediaLibrary.getMediaLibrary();
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
...@@ -46,14 +45,31 @@ async function getFd(pathName) { ...@@ -46,14 +45,31 @@ async function getFd(pathName) {
let fetchFileResult = await mediaTest.getFileAssets(fetchOp); let fetchFileResult = await mediaTest.getFileAssets(fetchOp);
let fileAsset = await fetchFileResult.getAllObject(); let fileAsset = await fetchFileResult.getAllObject();
let fdNumber = await fileAsset[0].open('Rw'); let fdNumber = await fileAsset[0].open('Rw');
fdNumber = "fd://" + fdNumber.toString(); this.testFdNumber = "fd://" + fdNumber.toString();
testFdNumber = fdNumber; }
} }
}
await getFd('01.mp4'); // 当发生错误上上报的错误回调接口
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);
}
let videoProfile = { // 当发生异常时,系统调用的错误回调接口
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);
}
async videoRecorderDemo() {
let videoRecorder = null; // videoRecorder空对象在createVideoRecorder成功后赋值
let surfaceID = null; // 用于保存getInputSurface返回的surfaceID
// 获取需要录制的视频的fd地址
await this.getFd('01.mp4');
// 录制相关参数配置
let videoProfile = {
audioBitrate : 48000, audioBitrate : 48000,
audioChannels : 2, audioChannels : 2,
audioCodec : 'audio/mp4a-latm', audioCodec : 'audio/mp4a-latm',
...@@ -64,36 +80,18 @@ let videoProfile = { ...@@ -64,36 +80,18 @@ let videoProfile = {
videoFrameWidth : 640, videoFrameWidth : 640,
videoFrameHeight : 480, videoFrameHeight : 480,
videoFrameRate : 30 videoFrameRate : 30
} }
let videoConfig = { let videoConfig = {
audioSourceType : 1, audioSourceType : 1,
videoSourceType : 0, videoSourceType : 0,
profile : videoProfile, profile : videoProfile,
url : testFdNumber, // testFdNumber由getFd生成 url : this.testFdNumber, // testFdNumber由getFd生成
orientationHint : 0, orientationHint : 0,
location : { latitude : 30, longitude : 130 }, location : { latitude : 30, longitude : 130 },
} }
// 创建videoRecorder对象
// 当发生错误上上报的错误回调接口 await media.createVideoRecorder().then((recorder) => {
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'); console.info('case createVideoRecorder called');
if (typeof (recorder) != 'undefined') { if (typeof (recorder) != 'undefined') {
videoRecorder = recorder; videoRecorder = recorder;
...@@ -101,48 +99,54 @@ await media.createVideoRecorder().then((recorder) => { ...@@ -101,48 +99,54 @@ await media.createVideoRecorder().then((recorder) => {
} else { } else {
console.info('createVideoRecorder failed'); console.info('createVideoRecorder failed');
} }
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// 获取surfaceID并保存下来传递给camera相关接口 // 调用prepare完成视频录制前的准备工作
await videoRecorder.getInputSurface().then((surface) => { await videoRecorder.prepare(videoConfig).then(() => {
console.info('prepare success');
}, this.failureCallback).catch(this.catchCallback);
// 获取surfaceID并保存下来传递给camera相关接口
await videoRecorder.getInputSurface().then((surface) => {
console.info('getInputSurface success'); console.info('getInputSurface success');
surfaceID = surface; surfaceID = surface;
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// 视频录制依赖相机相关接口,以下需要先调用相机起流接口后才能继续执行
// 视频录制启动接口 // 视频录制依赖相机相关接口,以下需要先调用相机起流接口后才能继续执行,具体的相机接口调用请参考sample用例
await videoRecorder.start().then(() => { // 视频录制启动接口
await videoRecorder.start().then(() => {
console.info('start success'); console.info('start success');
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// 调用pause接口时需要暂停camera出流 // 调用pause接口时需要暂停camera出流
await videoRecorder.pause().then(() => { await videoRecorder.pause().then(() => {
console.info('pause success'); console.info('pause success');
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// 调用resume接口时需要恢复camera出流 // 调用resume接口时需要恢复camera出流
await videoRecorder.resume().then(() => { await videoRecorder.resume().then(() => {
console.info('resume success'); console.info('resume success');
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// 停止camera出流后,停止视频录制 // 停止camera出流后,停止视频录制
await videoRecorder.stop().then(() => { await videoRecorder.stop().then(() => {
console.info('stop success'); console.info('stop success');
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// 重置录制相关配置 // 重置录制相关配置
await videoRecorder.reset().then(() => { await videoRecorder.reset().then(() => {
console.info('reset success'); console.info('reset success');
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// 释放视频录制相关资源并释放camera对象相关资源 // 释放视频录制相关资源并释放camera对象相关资源
await videoRecorder.release().then(() => { await videoRecorder.release().then(() => {
console.info('release success'); console.info('release success');
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// 相关对象置null // 相关对象置null
videoRecorder = null; videoRecorder = undefined;
surfaceID = null; surfaceID = undefined;
}
}
``` ```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册