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

!3953 翻译完成:3383 音频播放demo修改

Merge pull request !3953 from wusongqing/TR3383
...@@ -22,32 +22,43 @@ For details about the APIs, see [AudioPlayer in the Media API](../reference/apis ...@@ -22,32 +22,43 @@ For details about the APIs, see [AudioPlayer in the Media API](../reference/apis
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 the player, and releasing resources. 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 the player, and releasing resources.
For details about the **src** media source input types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_attributes). For details about the **src** types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_attributes).
```js ```js
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) { // Print the stream track information.
function printfDescription(obj) {
for (let item in obj) {
let property = obj[item];
console.info('audio key is ' + item);
console.info('audio value is ' + property);
}
}
// Set the player callbacks.
function setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
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.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered.
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
// The Play button is changed to the pausable state. audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
}); });
audioPlayer.on('pause', () => { // Set the 'pause' event callback. audioPlayer.on('pause', () => { // Set the 'pause' event callback.
console.info('audio pause success'); console.info('audio pause success');
// The Play button is changed to the playable state. audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback.
}); });
audioPlayer.on('stop', () => { // Set the 'stop' event callback. audioPlayer.on('stop', () => { // Set the 'stop' event callback.
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.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
}); });
audioPlayer.on('reset', () => { // Set the 'reset' event callback. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio reset success'); console.info('audio reset success');
// You can reconfigure the src attribute to play another audio file. audioPlayer.release(); // Release the AudioPlayer resources.
audioPlayer = undefined;
}); });
audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback. audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback.
if (typeof(seekDoneTime) == 'undefined') { if (typeof(seekDoneTime) == 'undefined') {
...@@ -55,72 +66,49 @@ function SetCallBack(audioPlayer) { ...@@ -55,72 +66,49 @@ 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);
// The playback progress bar is updated to the seek position. audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
}); });
audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
console.info('audio volumeChange success'); console.info('audio volumeChange success');
// Display the updated volume. 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]);
}
} else {
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback.
});
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish'); console.info('audio play finish');
}); });
audioPlayer.on('error', (error) => { // Set the 'error' event callback. audioPlayer.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, 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}`);
}); });
} }
function printfDescription(obj) { async function audioPlayerDemo() {
for (let item in obj) { // 1. Create an audioPlayer instance.
let property = obj[item]; let audioPlayer = media.createAudioPlayer();
console.info('audio key is ' + item); setCallBack(audioPlayer); // Set the event callbacks.
console.info('audio value is ' + property); // 2. Set the URI of the audio file selected by the user.
} let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
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;
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.
} }
// 1. Create an audioPlayer instance.
let audioPlayer = media.createAudioPlayer();
SetCallBack(audioPlayer); // Set the event callbacks.
// 2. Set the URI of the audio file selected by the user.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command.
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
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 file.
audioPlayer.play(); // The play() API 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]);
}
} else {
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
});
// 8. Stop the playback.
audioPlayer.stop(); // Trigger the 'stop' event callback.
// 9. Reset the player.
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 ### Normal Playback Scenario
...@@ -128,38 +116,40 @@ audioPlayer = undefined; ...@@ -128,38 +116,40 @@ 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) { // Set the player callbacks.
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
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', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish'); console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer.release(); // Release the AudioPlayer resources.
audioPlayer = undefined; audioPlayer = undefined;
});
}
async audioPlayerDemo() {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
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;
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.
}
} }
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://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command.
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
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 ### Switching to the Next Song
...@@ -167,54 +157,62 @@ audioPlayer.src = fdPath; // Set the src attribute and ...@@ -167,54 +157,62 @@ audioPlayer.src = fdPath; // Set the src attribute and
```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) { // Set the player callbacks.
private isNextMusic = false;
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback.
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio play finish'); console.info('audio play success');
if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented.
this.nextMusic(audioPlayer); // Changing songs is implemented.
} else {
audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined; audioPlayer = undefined;
}
});
}
async nextMusic(audioPlayer) {
this.isNextMusic = true;
let nextFdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "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" command.
let nextpath = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/02.mp3';
await fileIO.open(nextpath).then((fdNumber) => {
nextFdPath = nextFdPath + '' + fdNumber;
console.info('open fd sucess fd is' + nextFdPath);
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
}
async audioPlayerDemo() {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
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;
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.
}
} }
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://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command.
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
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();
/* Set the FD (local playback) of the audio file selected by the user. */
let fdNextPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/accounts/account_0/appdata" command.
let nextPath = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/02.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 ### Looping a Song
...@@ -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) { // Set the player callbacks.
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.loop = true; // Set the loop playback attribute.
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { // Sets the 'play' event callback to start loop playback.
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. }
console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance. async audioPlayerDemo() {
audioPlayer = undefined; let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
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;
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.
}
} }
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://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command.
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
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.
``` ```
## Samples ## Samples
...@@ -263,7 +257,6 @@ audioPlayer.loop = true; // Set the loop playback att ...@@ -263,7 +257,6 @@ audioPlayer.loop = true; // Set the loop playback att
The following samples are provided to help you better understand how to develop audio playback: The following samples are provided to help you better understand how to develop audio playback:
- [`JsDistributedMusicPlayer`: Distributed Music Player (JS) (API7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer) - [`JsDistributedMusicPlayer`: Distributed Music Player (JS) (API7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer)
- [`JsAudioPlayer`: Audio Playback and Management (JS, API 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer)
- [`JsAudioPlayer`: Audio Playback and Management (JS) (API7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer) - [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) - [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -25,46 +25,49 @@ The full audio recording process includes creating an instance, setting recordin ...@@ -25,46 +25,49 @@ The full audio recording process includes creating an instance, setting recordin
```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 {
let testFdNumber; private testFdNumber; // Used to save the FD address.
function SetCallBack(audioRecorder) { // Set the callbacks related to audio recording.
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. setCallBack(audioRecorder) {
console.log('prepare success'); audioRecorder.on('prepare', () => { // Set the 'prepare' event callback.
// The recording page is ready. You can click the Record button to start recording. console.log('prepare success');
audioRecorder.start(); // Call the start API to start recording and trigger the 'start' event callback.
}); });
audioRecorder.on('start', () => { // Set the 'start' event callback. audioRecorder.on('start', () => { // Set the 'start' event callback.
console.log('audio recorder start success'); console.log('audio recorder start success');
// The Record button is changed to the pausable state. audioRecorder.pause(); // Call the pause API to pause recording and trigger the 'pause' event callback.
}); });
audioRecorder.on('pause', () => { // Set the 'pause' event callback. audioRecorder.on('pause', () => { // Set the 'pause' event callback.
console.log('audio recorder pause success'); console.log('audio recorder pause success');
// The Record button is changed to the recordable state. audioRecorder.resume(); // Call the resume API to resume recording and trigger the 'resume' event callback.
}); });
audioRecorder.on('resume', () => { // Set the 'resume' event callback. audioRecorder.on('resume', () => { // Set the 'resume' event callback.
console.log('audio recorder resume success'); console.log('audio recorder resume success');
// The Record button is changed to the pausable state. audioRecorder.stop(); // Call the stop API to stop recording and trigger the 'stop' event callback.
}); });
audioRecorder.on('stop', () => { // Set the 'stop' event callback. audioRecorder.on('stop', () => { // Set the 'stop' event callback.
console.log('audio recorder stop success'); console.log('audio recorder stop success');
audioRecorder.reset(); // Call the reset API to reset the recorder and trigger the 'reset' event callback.
}); });
audioRecorder.on('release', () => { // Set the 'release' event callback. audioRecorder.on('reset', () => { // Set the 'reset' event callback.
console.log('audio recorder release success'); console.log('audio recorder reset success');
audioRecorder.release(); // Call the release API to release resources and trigger the 'release' event callback.
}); });
audioRecorder.on('reset', () => { // Set the 'reset' event callback. audioRecorder.on('release', () => { // Set the 'release' event callback.
console.log('audio recorder reset success'); console.log('audio recorder release success');
// You need to reset the recording parameters for another recording. audioRecorder = undefined;
}); });
audioRecorder.on('error', (error) => { // Set the 'error' event callback. audioRecorder.on('error', (error) => { // Set the 'error' event callback.
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. // pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Video/01.mp3.
// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. // 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) { 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;
...@@ -72,49 +75,37 @@ async function getFd(pathName) { ...@@ -72,49 +75,37 @@ async function getFd(pathName) {
let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO);
let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath);
if (dataUri != undefined) { if (dataUri != undefined) {
let args = dataUri.id.toString(); let args = dataUri.id.toString();
let fetchOp = { let fetchOp = {
selections : fileKeyObj.ID + "=?", selections : fileKeyObj.ID + "=?",
selectionArgs : [args], selectionArgs : [args],
} }
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;
} }
}
async audioRecorderDemo() {
// 1. Create an AudioRecorder instance.
let audioRecorder = media.createAudioRecorder();
// 2. Set the callbacks.
this.setCallBack(audioRecorder);
await this.getFd('01.mp3'); // Call the getFd method to obtain the FD address of the file to be recorded.
// 3. Set the recording parameters.
let audioRecorderConfig = {
audioEncodeBitRate : 22050,
audioSampleRate : 22050,
numberOfChannels : 2,
uri : this.testFdNumber, // testFdNumber is generated by getFd.
location : { latitude : 30, longitude : 130},
audioEncoderMime : media.CodecMimeType.AUDIO_AAC,
fileFormat : media.ContainerFormatType.CFT_MPEG_4A,
}
audioRecorder.prepare(audioRecorderConfig); // Call the prepare method to trigger the 'prepare' event callback.
}
} }
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 API can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete.
// 5. Pause recording.
audioRecorder.pause(); // The pause API can be called to trigger the 'pause' event callback only after the 'start' event callback is complete.
// 6. Resume recording.
audioRecorder.resume(); // The resume API can be called to trigger the 'resume' event callback only after the 'pause' event callback is complete.
// 7. Stop recording.
audioRecorder.stop(); // The stop API 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 API 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 ### Normal Recording Scenario
...@@ -124,29 +115,37 @@ Unlike the full-process scenario, the normal recording scenario does not include ...@@ -124,29 +115,37 @@ Unlike the full-process scenario, the normal recording scenario does not include
```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 {
let testFdNumber; private testFdNumber; // Used to save the FD address.
function SetCallBack(audioRecorder) { // Set the callbacks related to audio recording.
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. setCallBack(audioRecorder) {
console.log('prepare success'); audioRecorder.on('prepare', () => { // Set the 'prepare' event callback.
// The recording page is ready. You can click the Record button to start recording. console.log('prepare success');
audioRecorder.start(); // Call the start API to start recording and trigger the 'start' event callback.
}); });
audioRecorder.on('start', () => { // Set the 'start' event callback. audioRecorder.on('start', () => { // Set the 'start' event callback.
console.log('audio recorder start success'); console.log('audio recorder start success');
// The Record button is changed to the pausable state. audioRecorder.stop(); // Call the stop API to stop recording and trigger the 'stop' event callback.
}); });
audioRecorder.on('stop', () => { // Set the 'stop' event callback. audioRecorder.on('stop', () => { // Set the 'stop' event callback.
console.log('audio recorder stop success'); console.log('audio recorder stop success');
}); audioRecorder.release(); // Call the release API to release resources and trigger the 'release' event callback.
audioRecorder.on('release', () => { // Set the 'release' event callback. });
console.log('audio recorder release success'); audioRecorder.on('release', () => { // Set the 'release' event callback.
}); console.log('audio recorder release success');
} audioRecorder = undefined;
});
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. // pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Video/01.mp3.
// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. // 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) { 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;
...@@ -154,41 +153,43 @@ async function getFd(pathName) { ...@@ -154,41 +153,43 @@ async function getFd(pathName) {
let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO);
let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath);
if (dataUri != undefined) { if (dataUri != undefined) {
let args = dataUri.id.toString(); let args = dataUri.id.toString();
let fetchOp = { let fetchOp = {
selections : fileKeyObj.ID + "=?", selections : fileKeyObj.ID + "=?",
selectionArgs : [args], selectionArgs : [args],
} }
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;
} }
}
async audioRecorderDemo() {
// 1. Create an AudioRecorder instance.
let audioRecorder = media.createAudioRecorder();
// 2. Set the callbacks.
this.setCallBack(audioRecorder);
await this.getFd('01.mp3'); // Call the getFd method to obtain the FD address of the file to be recorded.
// 3. Set the recording parameters.
let audioRecorderConfig = {
audioEncodeBitRate : 22050,
audioSampleRate : 22050,
numberOfChannels : 2,
uri : this.testFdNumber, // testFdNumber is generated by getFd.
location : { latitude : 30, longitude : 130},
audioEncoderMime : media.CodecMimeType.AUDIO_AAC,
fileFormat : media.ContainerFormatType.CFT_MPEG_4A,
}
audioRecorder.prepare(audioRecorderConfig); // Call the prepare method to trigger the 'prepare' event callback.
}
} }
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 API can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete.
// 5. Stop recording.
audioRecorder.stop(); // The stop API 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;
``` ```
## Samples
The following samples are provided to help you better understand how to develop audio recording:
- [`Recorder`: Recorder (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
## When to Use ## When to Use
You can use video playback APIs to convert video data into visible signals, play the signals using output devices, and manage playback tasks. This document describes the following video playback development scenarios: full-process, normal playback, video switching, and loop playback. You can use video playback APIs to convert video data into visible signals, play the signals using output devices, and manage playback tasks. This document describes development for the following video playback scenarios: full-process, normal playback, video switching, and loop playback.
**Figure 1** Video playback state transition **Figure 1** Video playback state transition
...@@ -22,11 +22,11 @@ Note: Video playback requires hardware capabilities such as display, audio, and ...@@ -22,11 +22,11 @@ Note: Video playback requires hardware capabilities such as display, audio, and
## Compatibility ## Compatibility
You are advised to use the mainstream playback formats and resolutions, rather than custom or abnormal streams to avoid playback failure, frame freezing, and artifacts. The system is not affected by incompatibility issues. If such an error occurs, you can exit stream playback mode. Use the mainstream playback formats and resolutions, rather than custom ones to avoid playback failures, frame freezing, and artifacts. The system is not affected by incompatibility issues. If such an issue occurs, you can exit stream playback mode.
The table below lists the mainstream playback formats and resolutions. The table below lists the mainstream playback formats and resolutions.
| Video Container Specification| Specification Description | Resolution | | Video Container Format| Description | Resolution |
| :----------: | :-----------------------------------------------: | :--------------------------------: | | :----------: | :-----------------------------------------------: | :--------------------------------: |
| mp4 | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p| | mp4 | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p|
| mkv | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p| | mkv | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p|
...@@ -41,143 +41,137 @@ For details about the APIs, see [VideoPlayer in the Media API](../reference/apis ...@@ -41,143 +41,137 @@ For details about the APIs, see [VideoPlayer in the Media API](../reference/apis
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. 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 the **url** 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-creation). For details about how to create an XComponent, see [XComponent](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md).
*Note: **SetSurface** must be called after the URL is set but before **Prepare** is called. *Note: **setSurface** must be called after the URL is set but before **prepare** is called.
```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 VideoPlayerDemo {
let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer API. // Report an error in the case of a function invocation failure.
let surfaceID = undefined; // Used to save the surface ID returned by the XComponent interface. failureCallback(error) {
// The LoadXcomponent() API is used to obtain the surface ID and save it to the **surfaceID** variable. This API 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}`); console.info(`error happened,error Name is ${error.name}`);
console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Code is ${error.code}`);
console.info(`error happened,error Message is ${error.message}`); console.info(`error happened,error Message is ${error.message}`);
} }
// Report an error in the case of a function invocation exception. // Report an error in the case of a function invocation exception.
function catchCallback(error) { catchCallback(error) {
console.info(`catch error happened,error Name is ${error.name}`); console.info(`catch error happened,error Name is ${error.name}`);
console.info(`catch error happened,error Code is ${error.code}`); console.info(`catch error happened,error Code is ${error.code}`);
console.info(`catch error happened,error Message is ${error.message}`); console.info(`catch error happened,error Message is ${error.message}`);
} }
// Used to print the video track information. // Used to print the video track information.
function printfDescription(obj) { printfDescription(obj) {
for (let item in obj) { for (let item in obj) {
let property = obj[item]; let property = obj[item];
console.info('key is ' + item); console.info('key is ' + item);
console.info('value is ' + property); console.info('value is ' + property);
} }
} }
// Call createVideoPlayer to create a VideoPlayer instance. async videoPlayerDemo() {
await media.createVideoPlayer().then((video) => { let videoPlayer = undefined;
if (typeof (video) != 'undefined') { let surfaceID = 'test' // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent interface. For details about the document link, see the method of creating the XComponent.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.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 createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') {
console.info('createVideoPlayer success!'); console.info('createVideoPlayer success!');
videoPlayer = video; videoPlayer = video;
} else { } else {
console.info('createVideoPlayer fail!'); console.info('createVideoPlayer fail!');
} }
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// Set the playback source URL for the player.
// Set the FD (local playback) of the video file selected by the user. videoPlayer.url = fdPath;
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command. // Set the surface ID to display the video image.
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; await videoPlayer.setDisplaySurface(surfaceID).then(() => {
await fileIO.open(path).then(fdNumber) => { console.info('setDisplaySurface success');
fdPath = fdPath + '' + fdNumber; }, this.failureCallback).catch(this.catchCallback);
console.info('open fd sucess fd is' + fdPath);
}, (err) => { // Call the prepare API to prepare for playback.
console.info('open fd failed err is' + err); await videoPlayer.prepare().then(() => {
}),catch((err) => { console.info('prepare success');
console.info('open fd failed err is' + err); }, this.failureCallback).catch(this.catchCallback);
});
// Call the play API to start playback.
videoPlayer.url = fdPath; await videoPlayer.play().then(() => {
console.info('play success');
// Set the surface ID to display the video image. }, this.failureCallback).catch(this.catchCallback);
await videoPlayer.setDisplaySurface(surfaceID).then(() => {
console.info('setDisplaySurface success'); // Pause playback.
}, failureCallback).catch(catchCallback); await videoPlayer.pause().then(() => {
console.info('pause success');
// Call the prepare interface to prepare for playback. }, this.failureCallback).catch(this.catchCallback);
await videoPlayer.prepare().then(() => {
console.info('prepare success'); // Use a promise to obtain the video track information.
}, failureCallback).catch(catchCallback); let arrayDescription;
await videoPlayer.getTrackDescription().then((arrlist) => {
// Call the play interface to start playback. if (typeof (arrlist) != 'undefined') {
await videoPlayer.play().then(() => {
console.info('play success');
}, failureCallback).catch(catchCallback);
// Pause playback.
await videoPlayer.pause().then(() => {
console.info('pause success');
}, failureCallback).catch(catchCallback);
// Use a promise to obtain the video track information.
let arrayDescription;
await videoPlayer.getTrackDescription().then((arrlist) => {
if (typeof (arrlist) != 'undefined') {
arrayDescription = arrlist; arrayDescription = arrlist;
} else { } else {
console.log('video getTrackDescription fail'); console.log('video getTrackDescription fail');
}
}, this.failureCallback).catch(this.catchCallback);
for (let i = 0; i < arrayDescription.length; i++) {
this.printfDescription(arrayDescription[i]);
} }
}, failureCallback).catch(catchCallback);
for (let i = 0; i < arrayDescription.length; i++) { // Seek to the 50s position. For details about the input parameters, see the interface document.
printfDescription(arrayDescription[i]); let seekTime = 50000;
await videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime) => {
console.info('seek success');
}, this.failureCallback).catch(this.catchCallback);
// Set the volume. For details about the input parameters, see the interface document.
let volume = 0.5;
await videoPlayer.setVolume(volume).then(() => {
console.info('setVolume success');
}, this.failureCallback).catch(this.catchCallback);
// Set the playback speed. For details about the input parameters, see the interface document.
let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X;
await videoPlayer.setSpeed(speed).then(() => {
console.info('setSpeed success');
}, this.failureCallback).catch(this.catchCallback);
// Stop playback.
await videoPlayer.stop().then(() => {
console.info('stop success');
}, this.failureCallback).catch(this.catchCallback);
// Reset the playback configuration.
await videoPlayer.reset().then(() => {
console.info('reset success');
}, this.failureCallback).catch(this.catchCallback);
// Release playback resources.
await videoPlayer.release().then(() => {
console.info('release success');
}, this.failureCallback).catch(this.catchCallback);
// Set the related instances to undefined.
videoPlayer = undefined;
surfaceID = undefined;
}
} }
// Seek to the 50s position. For details about the input parameters, see the interface document.
let seekTime = 50000;
await videoPlayer.seek(seekTime, media.SeekMode._NEXT_SYNC).then((seekDoneTime) => {
console.info('seek success');
}, failureCallback).catch(catchCallback);
// Set the volume. For details about the input parameters, see the interface document.
let volume = 0.5;
await videoPlayer.setVolume(volume).then(() => {
console.info('setVolume success');
}, failureCallback).catch(catchCallback);
// Set the playback speed. For details about the input parameters, see the interface document.
let speed = media.PlaybackRateMode.SPEED_FORWARD_2_00_X;
await videoPlayer.setSpeed(speed).then(() => {
console.info('setSpeed success');
}, failureCallback).catch(catchCallback);
// Stop playback.
await videoPlayer.stop().then(() => {
console.info('stop success');
}, failureCallback).catch(catchCallback);
// Reset the playback configuration.
await videoPlayer.reset().then(() => {
console.info('reset success');
}, failureCallback).catch(catchCallback);
// Release playback resources.
await videoPlayer.release().then(() => {
console.info('release success');
}, failureCallback).catch(catchCallback);
// Set the related instances to undefined.
videoPlayer = undefined;
surfaceID = undefined;
``` ```
### Normal Playback Scenario ### Normal Playback Scenario
...@@ -185,86 +179,86 @@ surfaceID = undefined; ...@@ -185,86 +179,86 @@ surfaceID = 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 VideoPlayerDemo {
let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer API. // Report an error in the case of a function invocation failure.
let surfaceID = undefined; // Used to save the surface ID returned by the XComponent interface. failureCallback(error) {
// The LoadXcomponent() API is used to obtain the surface ID and save it to the **surfaceID** variable. This API 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}`); console.info(`error happened,error Name is ${error.name}`);
console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Code is ${error.code}`);
console.info(`error happened,error Message is ${error.message}`); console.info(`error happened,error Message is ${error.message}`);
} }
// Report an error in the case of a function invocation exception. // Report an error in the case of a function invocation exception.
function catchCallback(error) { catchCallback(error) {
console.info(`catch error happened,error Name is ${error.name}`); console.info(`catch error happened,error Name is ${error.name}`);
console.info(`catch error happened,error Code is ${error.code}`); console.info(`catch error happened,error Code is ${error.code}`);
console.info(`catch error happened,error Message is ${error.message}`); console.info(`catch error happened,error Message is ${error.message}`);
} }
// Set the 'playbackCompleted' event callback, which is triggered when the playback is complete. // Used to print the video track information.
function SetCallBack(videoPlayer) { printfDescription(obj) {
videoPlayer.on('playbackCompleted', () => { for (let item in obj) {
console.info('video play finish'); let property = obj[item];
console.info('key is ' + item);
await videoPlayer.release().then(() => { console.info('value is ' + property);
console.info('release success'); }
}, failureCallback).catch(catchCallback); }
videoPlayer = undefined; async videoPlayerDemo() {
surfaceID = undefined; let videoPlayer = undefined;
let surfaceID = 'test' // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent interface. For details about the document link, see the method of creating the XComponent.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.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 createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => {
// Call createVideoPlayer to create a VideoPlayer instance. if (typeof (video) != 'undefined') {
await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') {
console.info('createVideoPlayer success!'); console.info('createVideoPlayer success!');
videoPlayer = video; videoPlayer = video;
} else { } else {
console.info('createVideoPlayer fail!'); console.info('createVideoPlayer fail!');
} }
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// Set the playback source for the player.
// Set the event callbacks. videoPlayer.url = fdPath;
SetCallBack(videoPlayer);
// Set the surface ID to display the video image.
// Set the FD (local playback) of the video file selected by the user. await videoPlayer.setDisplaySurface(surfaceID).then(() => {
let fdPath = 'fd://' console.info('setDisplaySurface success');
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command. }, this.failureCallback).catch(this.catchCallback);
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4';
await fileIO.open(path).then(fdNumber) => { // Call the prepare API to prepare for playback.
fdPath = fdPath + '' + fdNumber; await videoPlayer.prepare().then(() => {
console.info('open fd sucess fd is' + fdPath); console.info('prepare success');
}, (err) => { }, this.failureCallback).catch(this.catchCallback);
console.info('open fd failed err is' + err);
}),catch((err) => { // Call the play API to start playback.
console.info('open fd failed err is' + err); await videoPlayer.play().then(() => {
}); console.info('play success');
}, this.failureCallback).catch(this.catchCallback);
videoPlayer.url = fdPath;
// Stop playback.
// Set the surface ID to display the video image. await videoPlayer.stop().then(() => {
await videoPlayer.setDisplaySurface(surfaceID).then(() => { console.info('stop success');
console.info('setDisplaySurface success'); }, this.failureCallback).catch(this.catchCallback);
}, failureCallback).catch(catchCallback);
// Release playback resources.
// Call the prepare interface to prepare for playback. await videoPlayer.release().then(() => {
await videoPlayer.prepare().then(() => { console.info('release success');
console.info('prepare success'); }, this.failureCallback).catch(this.catchCallback);
}, failureCallback).catch(catchCallback);
// Set the related instances to undefined.
// Call the play interface to start playback. videoPlayer = undefined;
await videoPlayer.play().then(() => { surfaceID = undefined;
console.info('play success'); }
}, failureCallback).catch(catchCallback); }
``` ```
### Switching to the Next Video Clip ### Switching to the Next Video Clip
...@@ -272,122 +266,110 @@ await videoPlayer.play().then(() => { ...@@ -272,122 +266,110 @@ await videoPlayer.play().then(() => {
```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 VideoPlayerDemo {
let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer API. // Report an error in the case of a function invocation failure.
let surfaceID = undefined; // Used to save the surface ID returned by the XComponent interface. failureCallback(error) {
// The LoadXcomponent() API is used to obtain the surface ID and save it to the **surfaceID** variable. This API 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}`); console.info(`error happened,error Name is ${error.name}`);
console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Code is ${error.code}`);
console.info(`error happened,error Message is ${error.message}`); console.info(`error happened,error Message is ${error.message}`);
} }
// Report an error in the case of a function invocation exception. // Report an error in the case of a function invocation exception.
function catchCallback(error) { catchCallback(error) {
console.info(`catch error happened,error Name is ${error.name}`); console.info(`catch error happened,error Name is ${error.name}`);
console.info(`catch error happened,error Code is ${error.code}`); console.info(`catch error happened,error Code is ${error.code}`);
console.info(`catch error happened,error Message is ${error.message}`); console.info(`catch error happened,error Message is ${error.message}`);
} }
// Set the 'playbackCompleted' event callback, which is triggered when the playback is complete. // Used to print the video track information.
function SetCallBack(videoPlayer) { printfDescription(obj) {
videoPlayer.on('playbackCompleted', () => { for (let item in obj) {
console.info('video play finish'); let property = obj[item];
console.info('key is ' + item);
await videoPlayer.release().then(() => { console.info('value is ' + property);
console.info('release success'); }
}, failureCallback).catch(catchCallback); }
videoPlayer = undefined; async videoPlayerDemo() {
surfaceID = undefined; let videoPlayer = undefined;
let surfaceID = 'test' // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent interface. For details about the document link, see the method of creating the XComponent.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
let nextPath = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/MP4_AAC.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 createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => {
// Call createVideoPlayer to create a VideoPlayer instance. if (typeof (video) != 'undefined') {
await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') {
console.info('createVideoPlayer success!'); console.info('createVideoPlayer success!');
videoPlayer = video; videoPlayer = video;
} else { } else {
console.info('createVideoPlayer fail!'); console.info('createVideoPlayer fail!');
} }
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// Set the playback source for the player.
// Set the event callbacks. videoPlayer.url = fdPath;
SetCallBack(videoPlayer);
// Set the surface ID to display the video image.
// Set the FD (local playback) of the video file selected by the user. await videoPlayer.setDisplaySurface(surfaceID).then(() => {
let fdPath = 'fd://' console.info('setDisplaySurface success');
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command. }, this.failureCallback).catch(this.catchCallback);
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4';
await fileIO.open(path).then(fdNumber) => { // Call the prepare API to prepare for playback.
fdPath = fdPath + '' + fdNumber; await videoPlayer.prepare().then(() => {
console.info('open fd sucess fd is' + fdPath); console.info('prepare success');
}, (err) => { }, this.failureCallback).catch(this.catchCallback);
console.info('open fd failed err is' + err);
}),catch((err) => { // Call the play API to start playback.
console.info('open fd failed err is' + err); await videoPlayer.play().then(() => {
}); console.info('play success');
}, this.failureCallback).catch(this.catchCallback);
videoPlayer.url = fdPath;
// Reset the playback configuration.
// Set the surface ID to display the video image. await videoPlayer.reset().then(() => {
await videoPlayer.setDisplaySurface(surfaceID).then(() => { console.info('reset success');
console.info('setDisplaySurface success'); }, this.failureCallback).catch(this.catchCallback);
}, failureCallback).catch(catchCallback);
// Obtain the next video FD address.
// Call the prepare interface to prepare for playback. fdPath = 'fd://'
await videoPlayer.prepare().then(() => { await fileIO.open(nextPath).then((fdNumber) => {
console.info('prepare success'); fdPath = fdPath + '' + fdNumber;
}, failureCallback).catch(catchCallback); console.info('open fd sucess fd is' + fdPath);
}, (err) => {
// Call the play interface to start playback. console.info('open fd failed err is' + err);
await videoPlayer.play().then(() => { }).catch((err) => {
console.info('play success'); console.info('open fd failed err is' + err);
}, failureCallback).catch(catchCallback); });
// Set the second video playback source.
// Send the instruction to switch to the next video clip after a period of time. videoPlayer.url = fdPath;
// Reset the playback configuration.
await videoPlayer.reset().then(() => { // Call the prepare interface to prepare for playback.
console.info('reset success'); await videoPlayer.prepare().then(() => {
}, failureCallback).catch(catchCallback); console.info('prepare success');
}, this.failureCallback).catch(this.catchCallback);
// Set the FD (local playback) of the video file selected by the user.
let fdNextPath = 'fd://' // Call the play API to start playback.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/accounts/account_0/appdata" command. await videoPlayer.play().then(() => {
let nextPath = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/02.mp4'; console.info('play success');
await fileIO.open(nextPath).then(fdNumber) => { }, this.failureCallback).catch(this.catchCallback);
fdNextPath = fdNextPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdNextPath); // Release playback resources.
}, (err) => { await videoPlayer.release().then(() => {
console.info('open fd failed err is' + err); console.info('release success');
}),catch((err) => { }, this.failureCallback).catch(this.catchCallback);
console.info('open fd failed err is' + err);
}); // Set the related instances to undefined.
videoPlayer = undefined;
videoPlayer.url = fdNextPath; surfaceID = undefined;
}
// Set the surface ID to display the video image. }
await videoPlayer.setDisplaySurface(surfaceID).then(() => {
console.info('setDisplaySurface success');
}, failureCallback).catch(catchCallback);
// Call the prepare interface to prepare for playback.
await videoPlayer.prepare().then(() => {
console.info('prepare success');
}, failureCallback).catch(catchCallback);
// Call the play interface to start playback.
await videoPlayer.play().then(() => {
console.info('play success');
}, failureCallback).catch(catchCallback);
``` ```
### Looping a Video Clip ### Looping a Video Clip
...@@ -395,100 +377,88 @@ await videoPlayer.play().then(() => { ...@@ -395,100 +377,88 @@ await videoPlayer.play().then(() => {
```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 VideoPlayerDemo {
let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer API. // Report an error in the case of a function invocation failure.
let surfaceID = undefined; // Used to save the surface ID returned by the XComponent interface. failureCallback(error) {
// The LoadXcomponent() API is used to obtain the surface ID and save it to the **surfaceID** variable. This API 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}`); console.info(`error happened,error Name is ${error.name}`);
console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Code is ${error.code}`);
console.info(`error happened,error Message is ${error.message}`); console.info(`error happened,error Message is ${error.message}`);
} }
// Report an error in the case of a function invocation exception. // Report an error in the case of a function invocation exception.
function catchCallback(error) { catchCallback(error) {
console.info(`catch error happened,error Name is ${error.name}`); console.info(`catch error happened,error Name is ${error.name}`);
console.info(`catch error happened,error Code is ${error.code}`); console.info(`catch error happened,error Code is ${error.code}`);
console.info(`catch error happened,error Message is ${error.message}`); console.info(`catch error happened,error Message is ${error.message}`);
} }
// Set the 'playbackCompleted' event callback, which is triggered when the playback is complete. // Used to print the video track information.
function SetCallBack(videoPlayer) { printfDescription(obj) {
videoPlayer.on('playbackCompleted', () => { for (let item in obj) {
console.info('video play finish'); let property = obj[item];
console.info('key is ' + item);
await videoPlayer.release().then(() => { console.info('value is ' + property);
console.info('release success'); }
}, failureCallback).catch(catchCallback); }
videoPlayer = undefined; sleep(time) {
surfaceID = undefined; for(let t = Date.now(); Date.now() - t <= time;);
}
async videoPlayerDemo() {
let videoPlayer = undefined;
let surfaceID = 'test' // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent interface. For details about the document link, see the method of creating the XComponent.
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.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 createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => {
// Call createVideoPlayer to create a VideoPlayer instance. if (typeof (video) != 'undefined') {
await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') {
console.info('createVideoPlayer success!'); console.info('createVideoPlayer success!');
videoPlayer = video; videoPlayer = video;
} else { } else {
console.info('createVideoPlayer fail!'); console.info('createVideoPlayer fail!');
} }
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// Set the playback source for the player.
// Set the event callbacks. videoPlayer.url = fdPath;
SetCallBack(videoPlayer);
// Set the surface ID to display the video image.
// Set the FD (local playback) of the video file selected by the user. await videoPlayer.setDisplaySurface(surfaceID).then(() => {
let fdPath = 'fd://' console.info('setDisplaySurface success');
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command. }, this.failureCallback).catch(this.catchCallback);
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4';
await fileIO.open(path).then(fdNumber) => { // Call the prepare API to prepare for playback.
fdPath = fdPath + '' + fdNumber; await videoPlayer.prepare().then(() => {
console.info('open fd sucess fd is' + fdPath); console.info('prepare success');
}, (err) => { }, this.failureCallback).catch(this.catchCallback);
console.info('open fd failed err is' + err); // Set the loop playback attribute.
}),catch((err) => { videoPlayer.loop = true;
console.info('open fd failed err is' + err); // Call the play API to start playback.
}); await videoPlayer.play().then(() => {
console.info('play success');
videoPlayer.url = fdPath; }, this.failureCallback).catch(this.catchCallback);
// After the progress bar reaches the end, the playback continues for 3 seconds and then starts from the beginning, since loop playback is configured.
// Set the surface ID to display the video image. await videoPlayer.seek(videoPlayer.duration, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime) => {
await videoPlayer.setDisplaySurface(surfaceID).then(() => { console.info('seek duration success');
console.info('setDisplaySurface success'); }, this.failureCallback).catch(this.catchCallback);
}, failureCallback).catch(catchCallback); this.sleep(3000);
// Release playback resources.
// Call the prepare interface to prepare for playback. await videoPlayer.release().then(() => {
await videoPlayer.prepare().then(() => { console.info('release success');
console.info('prepare success'); }, this.failureCallback).catch(this.catchCallback);
}, failureCallback).catch(catchCallback);
// Set the related instances to undefined.
// Set the loop playback attribute. videoPlayer = undefined;
videoPlayer.loop = true; surfaceID = undefined;
}
// Call the play interface to start playback. }
await videoPlayer.play().then(() => {
console.info('play success');
}, failureCallback).catch(catchCallback);
```
### XComponent Creation
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:
```js
<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.
``` ```
...@@ -16,21 +16,20 @@ During video recording, audio and video signals are captured, encoded, and saved ...@@ -16,21 +16,20 @@ During video recording, audio and video signals are captured, encoded, and saved
## How to Develop ## How to Develop
For details about the APIs used for video recording, see [VideoRecorder in the Media API](../reference/apis/js-apis-media.md). For details about the APIs, see [VideoRecorder in the Media API](../reference/apis/js-apis-media.md).
### Full-Process Scenario ### 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. The full video 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 media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary' import mediaLibrary from '@ohos.multimedia.mediaLibrary'
export class VideoRecorderDemo {
let testFdNumber; private testFdNumber; // Used to save the FD address.
// pathName indicates the passed recording file name, for example, 01.mp4. The generated file address is /storage/media/100/local/files/Video/01.mp4.
// 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.
// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and 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;
...@@ -38,110 +37,115 @@ async function getFd(pathName) { ...@@ -38,110 +37,115 @@ async function getFd(pathName) {
let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO);
let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath);
if (dataUri != undefined) { if (dataUri != undefined) {
let args = dataUri.id.toString(); let args = dataUri.id.toString();
let fetchOp = { let fetchOp = {
selections : fileKeyObj.ID + "=?", selections : fileKeyObj.ID + "=?",
selectionArgs : [args], selectionArgs : [args],
} }
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; }
}
// Error callback triggered in the case of an error
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
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 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.
// Obtain the FD address of the video to be recorded.
await this.getFd('01.mp4');
// Recording-related parameter settings
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
} }
}
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 = { let videoConfig = {
audioSourceType : 1, audioSourceType : 1,
videoSourceType : 0, videoSourceType : 0,
profile : videoProfile, profile : videoProfile,
url: testFdNumber, // testFdNumber is generated by getFd. url : this.testFdNumber, // testFdNumber is generated by getFd.
orientationHint : 0, orientationHint : 0,
location : { latitude : 30, longitude : 130 }, location : { latitude : 30, longitude : 130 },
} }
// Create a VideoRecorder object.
// Error callback triggered in the case of an error await media.createVideoRecorder().then((recorder) => {
function failureCallback(error) { console.info('case createVideoRecorder called');
console.info('error happened, error name is ' + error.name); if (typeof (recorder) != 'undefined') {
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; videoRecorder = recorder;
console.info('createVideoRecorder success'); console.info('createVideoRecorder success');
} else { } else {
console.info('createVideoRecorder failed'); console.info('createVideoRecorder failed');
} }
}, failureCallback).catch(catchCallback); }, this.failureCallback).catch(this.catchCallback);
// Obtain the surface ID, save it, and pass it to camera-related interfaces. // Call the prepare API to prepare for video recording.
await videoRecorder.getInputSurface().then((surface) => { await videoRecorder.prepare(videoConfig).then(() => {
console.info('getInputSurface success'); console.info('prepare success');
surfaceID = surface; }, this.failureCallback).catch(this.catchCallback);
}, failureCallback).catch(catchCallback);
// Obtain the surface ID, save it, and pass it to camera-related APIs.
// Video recording depends on camera-related interfaces. The following operations can be performed only after the video output start interface is invoked. await videoRecorder.getInputSurface().then((surface) => {
console.info('getInputSurface success');
// Start video recording. surfaceID = surface;
await videoRecorder.start().then(() => { }, this.failureCallback).catch(this.catchCallback);
console.info('start success');
}, failureCallback).catch(catchCallback); // Video recording depends on camera-related APIs. The following operations can be performed only after the video output start API is invoked. For details about how to call the camera APIs, see the samples.
// Start video recording.
// Pause video playback before the video output stop interface is invoked. await videoRecorder.start().then(() => {
await videoRecorder.pause().then(() => { console.info('start success');
console.info('pause success'); }, this.failureCallback).catch(this.catchCallback);
}, failureCallback).catch(catchCallback);
// Pause video recording before the video output stop API of the camera is invoked.
// Resume video playback after the video output start interface is invoked. await videoRecorder.pause().then(() => {
await videoRecorder.resume().then(() => { console.info('pause success');
console.info('resume success'); }, this.failureCallback).catch(this.catchCallback);
}, failureCallback).catch(catchCallback);
// Resume video recording after the video output start API of the camera is invoked.
// Stop video recording after the video output stop interface is invoked. await videoRecorder.resume().then(() => {
await videoRecorder.stop().then(() => { console.info('resume success');
console.info('stop success'); }, this.failureCallback).catch(this.catchCallback);
}, failureCallback).catch(catchCallback);
// Stop video recording after the video output stop API of the camera is invoked.
// Reset the recording configuration. await videoRecorder.stop().then(() => {
await videoRecorder.reset().then(() => { console.info('stop success');
console.info('reset success'); }, this.failureCallback).catch(this.catchCallback);
}, failureCallback).catch(catchCallback);
// Reset the recording configuration.
// Release the video recording resources and camera object resources. await videoRecorder.reset().then(() => {
await videoRecorder.release().then(() => { console.info('reset success');
console.info('release success'); }, this.failureCallback).catch(this.catchCallback);
}, failureCallback).catch(catchCallback);
// Release the video recording resources and camera object resources.
// Set the related object to null. await videoRecorder.release().then(() => {
videoRecorder = null; console.info('release success');
surfaceID = null; }, this.failureCallback).catch(this.catchCallback);
// Set the related object to null.
videoRecorder = undefined;
surfaceID = undefined;
}
}
``` ```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册