From 3323f4f5a8d743010aeea0680f931334a5f2a93b Mon Sep 17 00:00:00 2001 From: wusongqing Date: Wed, 16 Mar 2022 17:22:49 +0800 Subject: [PATCH 1/4] Updated docs Signed-off-by: wusongqing --- en/application-dev/media/audio-playback.md | 87 +- en/application-dev/media/audio-recorder.md | 65 +- en/application-dev/media/video-playback.md | 126 +- en/application-dev/media/video-recorder.md | 33 +- .../reference/apis/js-apis-media.md | 2160 +++++++++++++++-- 5 files changed, 2238 insertions(+), 233 deletions(-) diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index 004be69abbe..20d926f009b 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -25,6 +25,9 @@ The full audio playback process includes creating an instance, setting the URI, For details about the **src** media source input types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_Attributes). ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + function SetCallBack(audioPlayer) { audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); @@ -80,7 +83,18 @@ function printfDescription(obj) { let audioPlayer = media.createAudioPlayer(); SetCallBack(audioPlayer); // Set the event callbacks. // 2. Set the URI of the audio file. -audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); + +audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. // 3. Play the audio. audioPlayer.play(); // The play() method can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is triggered. // 4. Seek to the playback position. @@ -111,6 +125,9 @@ audioPlayer = undefined; ### Normal Playback Scenario ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + function SetCallBack(audioPlayer) { audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); @@ -128,13 +145,27 @@ function SetCallBack(audioPlayer) { let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. SetCallBack(audioPlayer); // Set the event callbacks. -/* Set the URI of the audio file selected by the user. */ -audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. +/* Set the FD (local playback) of the audio file selected by the user. */ +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); + +audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. ``` ### Switching to the Next Song ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + function SetCallBack(audioPlayer) { audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); @@ -152,16 +183,42 @@ function SetCallBack(audioPlayer) { let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. SetCallBack(audioPlayer); // Set the event callbacks. -/* Set the URI of the audio file selected by the user. */ -audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. +/* Set the FD (local playback) of the audio file selected by the user. */ +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); + +audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. /* Send the instruction to switch to the next song after a period of time. */ audioPlayer.reset(); -audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/next.mp3'; + +/* Set the FD (local playback) of the audio file selected by the user. */ +let fdNextPath = 'fd://' +let nextPath = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +await fileIO.open(nextPath).then(fdNumber) => { + fdNextPath = fdNextPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdNextPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); +audioPlayer.src = fdNextPath; ``` ### Looping a Song ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + function SetCallBack(audioPlayer) { audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); @@ -179,7 +236,19 @@ function SetCallBack(audioPlayer) { let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. SetCallBack(audioPlayer); // Set the event callbacks. -/* Set the URI of the audio file selected by the user. */ -audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. -audioPlayer.loop = true; // Set the loop playback attribute. + +/* Set the FD (local playback) of the audio file selected by the user. */ +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); + +audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. +audioPlayer.loop = true; // Set the loop playback attribute. ``` diff --git a/en/application-dev/media/audio-recorder.md b/en/application-dev/media/audio-recorder.md index 8468c7e8151..0eed7ce6e20 100644 --- a/en/application-dev/media/audio-recorder.md +++ b/en/application-dev/media/audio-recorder.md @@ -23,6 +23,11 @@ For details about the APIs used for audio recording, see [js-apis-media.md](../r The full audio recording process includes creating an instance, setting recording parameters, starting, pausing, resuming, and stopping recording, and releasing resources. ```js +import media from '@ohos.multimedia.media' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +let testFdNumber; + function SetCallBack(audioRecorder) { audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. console.log('prepare success'); @@ -57,6 +62,31 @@ function SetCallBack(audioRecorder) { }); } +// pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Movies/01.mp3. +// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. +async function getFd(pathName) { + let displayName = pathName; + const mediaTest = mediaLibrary.getMediaLibrary(); + let fileKeyObj = mediaLibrary.FileKey; + let mediaType = mediaLibrary.MediaType.VIDEO; + let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); + let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); + if (dataUri != undefined) { + let args = dataUri.id.toString(); + let fetchOp = { + selections : fileKeyObj.ID + "=?", + selectionArgs : [args], + } + let fetchFileResult = await mediaTest.getFileAssets(fetchOp); + let fileAsset = await fetchFileResult.getAllObject(); + let fdNumber = await fileAsset[0].open('Rw'); + fdNumber = "fd://" + fdNumber.toString(); + testFdNumber = fdNumber; + } +} + +await getFd('01.mp3'); + // 1. Create an AudioRecorder instance. let audioRecorder = media.createAudioRecorder(); // 2. Set the callbacks. @@ -68,7 +98,7 @@ let audioRecorderConfig = { audioSampleRate : 22050, numberOfChannels : 2, format : media.AudioOutputFormat.AAC_ADTS, - uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', // The file must be created by the caller and granted with proper permissions. + uri : testFdNumber, // testFdNumber is generated by getFd. location : { latitude : 30, longitude : 130}, } audioRecorder.prepare(audioRecorderConfig); @@ -92,6 +122,11 @@ audioRecorder = undefined; Unlike the full-process scenario, the normal recording scenario does not include the process of pausing and resuming recording. ```js +import media from '@ohos.multimedia.media' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +let testFdNumber; + function SetCallBack(audioPlayer) { audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. console.log('prepare success'); @@ -108,6 +143,32 @@ function SetCallBack(audioPlayer) { console.log('audio recorder release success'); }); } + +// pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Movies/01.mp3. +// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. +async function getFd(pathName) { + let displayName = pathName; + const mediaTest = mediaLibrary.getMediaLibrary(); + let fileKeyObj = mediaLibrary.FileKey; + let mediaType = mediaLibrary.MediaType.VIDEO; + let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); + let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); + if (dataUri != undefined) { + let args = dataUri.id.toString(); + let fetchOp = { + selections : fileKeyObj.ID + "=?", + selectionArgs : [args], + } + let fetchFileResult = await mediaTest.getFileAssets(fetchOp); + let fileAsset = await fetchFileResult.getAllObject(); + let fdNumber = await fileAsset[0].open('Rw'); + fdNumber = "fd://" + fdNumber.toString(); + testFdNumber = fdNumber; + } +} + +await getFd('01.mp3'); + // 1. Create an AudioRecorder instance. let audioRecorder = media.createAudioRecorder(); // 2. Set the callbacks. @@ -119,7 +180,7 @@ let audioRecorderConfig = { audioSampleRate : 22050, numberOfChannels : 2, format : media.AudioOutputFormat.AAC_ADTS, - uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', // The file must be created by the caller and granted with proper permissions. + uri : testFdNumber, // testFdNumber is generated by getFd. location : { latitude : 30, longitude : 130}, } audioRecorder.prepare(audioRecorderConfig) diff --git a/en/application-dev/media/video-playback.md b/en/application-dev/media/video-playback.md index 23bf8b98dbd..d15b8f22e0f 100644 --- a/en/application-dev/media/video-playback.md +++ b/en/application-dev/media/video-playback.md @@ -28,10 +28,23 @@ For details about the APIs used for video playback, see [js-apis-media.md](../re The full video playback process includes creating an instance, setting the URL, setting the surface ID, preparing for video playback, playing video, pausing playback, obtaining track information, seeking to a playback position, setting the volume, setting the playback speed, stopping playback, resetting the playback configuration, and releasing resources. +For details about the **url** media source input types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_Attributes). + +For details about how to create an Xcomponent, see [Xcomponent Creation](#Xcomponent). + ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method. let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface. +// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded. +LoadXcomponent() { + surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); + console.info('LoadXcomponent surfaceID is' + surfaceID); +} + // Report an error in the case of a function invocation failure. function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); @@ -65,10 +78,19 @@ await media.createVideoPlayer().then((video) => { } }, failureCallback).catch(catchCallback); -// Set the URL of the video file selected by the user. -videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; +// Set the FD (local playback) of the video file selected by the user. +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); -// Call the Xcomponent interface to obtain the surface ID and save it to the surfaceID variable. +videoPlayer.url = fdPath; // Set the surface ID to display the video image. await videoPlayer.setDisplaySurface(surfaceID).then(() => { @@ -145,9 +167,18 @@ surfaceID = undefined; ### Normal Playback Scenario ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method. let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface. +// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded. +LoadXcomponent() { + surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); + console.info('LoadXcomponent surfaceID is' + surfaceID); +} + // Report an error in the case of a function invocation failure. function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); @@ -189,10 +220,19 @@ await media.createVideoPlayer().then((video) => { // Set the event callbacks. SetCallBack(videoPlayer); -// Set the URL of the video file selected by the user. -videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; +// Set the FD (local playback) of the video file selected by the user. +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); -// Call the Xcomponent interface to obtain the surface ID and save it to the surfaceID variable. +videoPlayer.url = fdPath; // Set the surface ID to display the video image. await videoPlayer.setDisplaySurface(surfaceID).then(() => { @@ -213,9 +253,18 @@ await videoPlayer.play().then(() => { ### Switching to the Next Video Clip ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method. let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface. +// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded. +LoadXcomponent() { + surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); + console.info('LoadXcomponent surfaceID is' + surfaceID); +} + // Report an error in the case of a function invocation failure. function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); @@ -257,10 +306,19 @@ await media.createVideoPlayer().then((video) => { // Set the event callbacks. SetCallBack(videoPlayer); -// Set the URL of the video file selected by the user. -videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; +// Set the FD (local playback) of the video file selected by the user. +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); -// Call the Xcomponent interface to obtain the surface ID and save it to the surfaceID variable. +videoPlayer.url = fdPath; // Set the surface ID to display the video image. await videoPlayer.setDisplaySurface(surfaceID).then(() => { @@ -283,7 +341,19 @@ await videoPlayer.reset().then(() => { console.info('reset success'); }, failureCallback).catch(catchCallback); -videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/next.mp4'; +// Set the FD (local playback) of the video file selected by the user. +let fdNextPath = 'fd://' +let nextPath = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/02.mp4'; +await fileIO.open(nextPath).then(fdNumber) => { + fdNextPath = fdNextPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdNextPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); + +videoPlayer.url = fdNextPath; // Set the surface ID to display the video image. await videoPlayer.setDisplaySurface(surfaceID).then(() => { @@ -304,9 +374,18 @@ await videoPlayer.play().then(() => { ### Looping a Video Clip ```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method. let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface. +// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded. +LoadXcomponent() { + surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); + console.info('LoadXcomponent surfaceID is' + surfaceID); +} + // Report an error in the case of a function invocation failure. function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); @@ -348,10 +427,19 @@ await media.createVideoPlayer().then((video) => { // Set the event callbacks. SetCallBack(videoPlayer); -// Set the URL of the video file selected by the user. -videoPlayer.url = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; +// Set the FD (local playback) of the video file selected by the user. +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); -// Call the Xcomponent interface to obtain the surface ID and save it to the surfaceID variable. +videoPlayer.url = fdPath; // Set the surface ID to display the video image. await videoPlayer.setDisplaySurface(surfaceID).then(() => { @@ -371,3 +459,15 @@ await videoPlayer.play().then(() => { console.info('play success'); }, failureCallback).catch(catchCallback); ``` + +### Xcomponent Creation + +```js +The Xcomponent is used to obtain the surface ID during video playback. You need to create an xxx.hml file and add the following code to the xxx.hml file, where xxx is the same as that in the xxx.js file: + // Set the window width, height, and other attributes. + +``` diff --git a/en/application-dev/media/video-recorder.md b/en/application-dev/media/video-recorder.md index 99de4412e8e..11af1d39846 100644 --- a/en/application-dev/media/video-recorder.md +++ b/en/application-dev/media/video-recorder.md @@ -23,6 +23,36 @@ For details about the APIs used for video recording, see [js-apis-media.md](../r The full video recording process includes creating an instance, setting recording parameters, recording video, pausing, resuming, and stopping recording, and releasing resources. ```js +import media from '@ohos.multimedia.media' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +let testFdNumber; + +// pathName indicates the passed recording file name, for example, 01.mp4. The generated file address is /storage/media/100/local/files/Movies/01.mp4. +// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. +async function getFd(pathName) { + let displayName = pathName; + const mediaTest = mediaLibrary.getMediaLibrary(); + let fileKeyObj = mediaLibrary.FileKey; + let mediaType = mediaLibrary.MediaType.VIDEO; + let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); + let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); + if (dataUri != undefined) { + let args = dataUri.id.toString(); + let fetchOp = { + selections : fileKeyObj.ID + "=?", + selectionArgs : [args], + } + let fetchFileResult = await mediaTest.getFileAssets(fetchOp); + let fileAsset = await fetchFileResult.getAllObject(); + let fdNumber = await fileAsset[0].open('Rw'); + fdNumber = "fd://" + fdNumber.toString(); + testFdNumber = fdNumber; + } +} + +await getFd('01.mp4'); + let videoProfile = { audioBitrate : 48000, audioChannels : 2, @@ -40,7 +70,7 @@ let videoConfig = { audioSourceType : 1, videoSourceType : 0, profile : videoProfile, - url : 'file:///data/media/01.mp4', + url: testFdNumber, // testFdNumber is generated by getFd. orientationHint : 0, location : { latitude : 30, longitude : 130 }, } @@ -61,6 +91,7 @@ function catchCallback(error) { let videoRecorder = null; // videoRecorder is an empty object and assigned with a value after createVideoRecorder is successfully called. let surfaceID = null; // Used to save the surface ID returned by getInputSurface. + // Create a VideoRecorder object. await media.createVideoRecorder().then((recorder) => { console.info('case createVideoRecorder called'); diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index c1814c9015d..6694e1bfbe8 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -1,13 +1,18 @@ # Media +> **NOTE** +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. This subsystem offers various media services covering audio and video, which provide the following capabilities: - Audio playback ([AudioPlayer](#audioplayer)) +- Video playback ([VideoPlayer](#videoplayer8)) - Audio recording ([AudioRecorder](#audiorecorder)) +- Video recording ([VideoRecorder](#VideoRecorder8+)) -The following capabilities will be provided in the future: video playback, video recording, data source audio/video playback, audio/video encoding and decoding, container encapsulation and decapsulation, and media capability query. +The following capabilities will be provided in later versions: data source audio/video playback, audio/video encoding and decoding, container encapsulation and decapsulation, and media capability query. ## Modules to Import @@ -21,179 +26,260 @@ createAudioPlayer(): [AudioPlayer](#audioplayer) Creates an **AudioPlayer** instance in synchronous mode. +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + **Return value** -| Type| Description| +| Type | Description | | --------------------------- | ------------------------------------------------------------ | | [AudioPlayer](#audioplayer) | Returns the **AudioPlayer** instance if the operation is successful; returns **null** otherwise. After the instance is created, you can start, pause, or stop audio playback.| **Example** ```js -var audioPlayer = media.createAudioPlayer(); +let audioPlayer = media.createAudioPlayer(); ``` -## media.createAudioPlayerAsync8+ +## media.createVideoPlayer8+ -createAudioPlayerAsync(callback: AsyncCallback\<[AudioPlayer](#audioplayer)>): void +createVideoPlayer(callback: AsyncCallback\<[VideoPlayer](#videoplayer8)>): void -Creates an **AudioPlayer** instance in asynchronous mode. This method uses a callback to return the result. +Creates a **VideoPlayer** instance in asynchronous mode. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer **Parameters** -| Name| Type| Mandatory| Description| -| -------- | ------------------------------------------ | ---- | ------------------------------ | -| callback | AsyncCallback<[AudioPlayer](#audioplayer)> | Yes| Callback used to return the **AudioPlayer** instance created.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the **VideoPlayer** instance created.| **Example** ```js -media.createAudioPlayerAsync((error, audio) => { - if (typeof(audio) != 'undefined') { - audioPlayer = audio; - console.info('audio createAudioPlayerAsync success'); +let videoPlayer + +media.createVideoPlayer((error, video) => { + if (typeof(video) != 'undefined') { + videoPlayer = video; + console.info('video createVideoPlayer success'); } else { - console.info(`audio createAudioPlayerAsync fail, error:${error.message}`); + console.info(`video createVideoPlayer fail, error:${error.message}`); } }); ``` -## media.createAudioPlayerAsync8+ +## media.createVideoPlayer8+ -createAudioPlayerAsync: Promise<[AudioPlayer](#audioplayer)> +createVideoPlayer: Promise<[VideoPlayer](#videoplayer8)> -Creates an **AudioPlayer** instance in asynchronous mode. This method uses a promise to return the result. +Creates a **VideoPlayer** instance in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer **Return value** -| Type| Description| -| ------------------------------------ | ----------------------------------- | -| Promise<[AudioPlayer](#audioplayer)> | Promise used to return the **AudioPlayer** instance created.| +| Type | Description | +| ------------------------------------- | ----------------------------------- | +| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the **VideoPlayer** instance created.| **Example** ```js +let videoPlayer + function failureCallback(error) { - console.info(`audio failureCallback, error:${error.message}`); + console.info(`video failureCallback, error:${error.message}`); } function catchCallback(error) { - console.info(`audio catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error.message}`); } -await media.createAudioPlayerAsync.then((audio) => { - if (typeof(audio) != 'undefined') { - audioPlayer = audio; - console.info('audio createAudioPlayerAsync success'); +await media.createVideoPlayer.then((video) => { + if (typeof(video) != 'undefined') { + videoPlayer = video; + console.info('video createVideoPlayer success'); } else { - console.info('audio createAudioPlayerAsync fail'); + console.info('video createVideoPlayer fail'); } }, failureCallback).catch(catchCallback); ``` ## media.createAudioRecorder + createAudioRecorder(): AudioRecorder Creates an **AudioRecorder** instance to control audio recording. +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + **Return value** -| Type| Description| +| Type | Description | | ------------------------------- | ----------------------------------------- | | [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise.| **Example** +```js +let audiorecorder = media.createAudioRecorder(); +``` + +## media.createVideoRecorder8+ + +createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder8)>): void + +Creates a **VideoRecorder** instance in asynchronous mode. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback<[VideoRecorder](#videorecorder8)> | Yes | Callback used to return the **VideoRecorder** instance created.| + +**Example** + +```js +let videoRecorder + +media.createVideoRecorder((error, video) => { + if (typeof(video) != 'undefined') { + videoRecorder = video; + console.info('video createVideoRecorder success'); + } else { + console.info(`video createVideoRecorder fail, error:${error.message}`); + } +}); ``` -var audiorecorder = media.createAudioRecorder(); + +## media.createVideoRecorder8+ + +createVideoRecorder: Promise<[VideoRecorder](#videorecorder8)> + +Creates a **VideoRecorder** instance in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Return value** + +| Type | Description | +| ----------------------------------------- | ----------------------------------- | +| Promise<[VideoRecorder](#videorecorder8)> | Promise used to return the **VideoRecorder** instance created.| + +**Example** + +```js +let videoRecorder + +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); +} + +await media.createVideoRecorder.then((video) => { + if (typeof(video) != 'undefined') { + videoRecorder = video; + console.info('video createVideoRecorder success'); + } else { + console.info('video createVideoRecorder fail'); + } +}, failureCallback).catch(catchCallback); ``` + + ## MediaErrorCode8+ Enumerates the media error codes. -| Name| Value| Description| -| -------------------------- | ---- | -------------------------------------- | -| MSERR_OK | 0 | The operation is successful.| -| MSERR_NO_MEMORY | 1 | Failed to allocate memory. The system may have no available memory.| -| MSERR_OPERATION_NOT_PERMIT | 2 | No permission to perform this operation.| -| MSERR_INVALID_VAL | 3 | Invalid input parameter.| -| MSERR_IO | 4 | An I/O error occurs.| -| MSERR_TIMEOUT | 5 | The operation times out.| -| MSERR_UNKNOWN | 6 | An unknown error occurs.| -| MSERR_SERVICE_DIED | 7 | Invalid server.| -| MSERR_INVALID_STATE | 8 | The operation is not allowed in the current state.| -| MSERR_UNSUPPORTED | 9 | The operation is not supported in the current version.| +| Name | Value | Description | +| -------------------------- | ---- | ------------------------------------------------------------ | +| MSERR_OK | 0 | The operation is successful.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_NO_MEMORY | 1 | Failed to allocate memory. The system may have no available memory.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_OPERATION_NOT_PERMIT | 2 | No permission to perform this operation.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_INVALID_VAL | 3 | Invalid input parameter.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_IO | 4 | An I/O error occurs.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_TIMEOUT | 5 | The operation times out.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_UNKNOWN | 6 | An unknown error occurs.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_SERVICE_DIED | 7 | Invalid server.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_INVALID_STATE | 8 | The operation is not allowed in the current state.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_UNSUPPORTED | 9 | The operation is not supported in the current version.
**System capability**: SystemCapability.Multimedia.Media.Core| ## MediaType8+ Enumerates the media types. -| Name| Value| Description| -| ------------------- | ---- | ------------------ | -| MEDIA_TYPE_AUD | 0 | Media.| -| MEDIA_TYPE_VID | 1 | Video.| -| MEDIA_TYPE_SUBTITLE | 2 | Subtitle. (under development)| +| Name | Value | Description | +| -------------- | ---- | ------------------------------------------------------------ | +| MEDIA_TYPE_AUD | 0 | Media.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MEDIA_TYPE_VID | 1 | Video.
**System capability**: SystemCapability.Multimedia.Media.Core| ## CodecMimeType8+ Enumerates the codec MIME types. -| Name| Value| Description| -| ------------ | ----------------- | ------------------------ | -| AUDIO_MPEG | "audio/mpeg" | Audio in MPEG format.| -| AUDIO_AAC | "audio/mp4a-latm" | Audio in MP4A-LATM format.| -| AUDIO_VORBIS | "audio/vorbis" | Audio in Vorbis format.| -| AUDIO_FLAC | "audio/flac" | Audio in FLAC format.| +| Name | Value | Description | +| ------------ | ----------------- | ------------------------------------------------------------ | +| VIDEO_MPEG4 | "video/mp4v-es" | Video in MPEG-4 format.
**System capability**: SystemCapability.Multimedia.Media.Core| +| AUDIO_AAC | "audio/mp4a-latm" | Audio in MP4A-LATM format.
**System capability**: SystemCapability.Multimedia.Media.Core| +| AUDIO_VORBIS | "audio/vorbis" | Audio in Vorbis format.
**System capability**: SystemCapability.Multimedia.Media.Core| +| AUDIO_FLAC | "audio/flac" | Audio in FLAC format.
**System capability**: SystemCapability.Multimedia.Media.Core| ## MediaDescriptionKey8+ Enumerates the media description keys. -| Name| Value| Description| +| Name | Value | Description | | ------------------------ | --------------- | ------------------------------------------------------------ | -| MD_KEY_TRACK_INDEX | "track_index" | Track index, which is a number.| -| MD_KEY_TRACK_TYPE | "track_type" | Track type, which is a number. For details, see [MediaType](#mediatype8).| -| MD_KEY_CODEC_MIME | "codec_mime" | Codec MIME type, which is a string.| -| MD_KEY_DURATION | "duration" | Media duration, which is a number, in units of ms.| -| MD_KEY_BITRATE | "bitrate" | Bit rate, which is a number, in units of bit/s.| -| MD_KEY_WIDTH | "width" | Video width, which is a number, in units of pixel.| -| MD_KEY_HEIGHT | "height" | Video height, which is a number, in units of pixel.| -| MD_KEY_FRAME_RATE | "frame_rate" | Video frame rate, which is a number, in units of 100 fps.| -| MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | Number of audio channels, which is a number.| -| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | Sampling rate, which is a number, in units of Hz.| +| MD_KEY_TRACK_INDEX | "track_index" | Track index, which is a number.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_TRACK_TYPE | "track_type" | Track type, which is a number. For details, see [MediaType](#mediatype8).
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_CODEC_MIME | "codec_mime" | Codec MIME type, which is a string.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_DURATION | "duration" | Media duration, which is a number, in units of ms.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_BITRATE | "bitrate" | Bit rate, which is a number, in units of bit/s.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_WIDTH | "width" | Video width, which is a number, in units of pixel.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_HEIGHT | "height" | Video height, which is a number, in units of pixel.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_FRAME_RATE | "frame_rate" | Video frame rate, which is a number, in units of 100 fps.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | Number of audio channels, which is a number.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | Sampling rate, which is a number, in units of Hz.
**System capability**: SystemCapability.Multimedia.Media.Core| ## BufferingInfoType8+ Enumerates the buffering event types. -| Name| Value| Description| -| ----------------- | ---- | -------------------------- | -| BUFFERING_START | 1 | Buffering starts.| -| BUFFERING_END | 2 | Buffering ends.| -| BUFFERING_PERCENT | 3 | Buffering progress, in percent.| -| CACHED_DURATION | 4 | Cache duration, in milliseconds.| +| Name | Value | Description | +| ----------------- | ---- | ------------------------------------------------------------ | +| BUFFERING_START | 1 | Buffering starts.
**System capability**: SystemCapability.Multimedia.Media.Core| +| BUFFERING_END | 2 | Buffering ends.
**System capability**: SystemCapability.Multimedia.Media.Core| +| BUFFERING_PERCENT | 3 | Buffering progress, in percent.
**System capability**: SystemCapability.Multimedia.Media.Core| +| CACHED_DURATION | 4 | Cache duration, in milliseconds.
**System capability**: SystemCapability.Multimedia.Media.Core| ## AudioPlayer -Manages and plays audio. Before calling a method of the **AudioPlayer** class, you must call [createAudioPlayer()](#media.createaudioplayer) or [createAudioPlayerAsync()](#media.createaudioplayerasync8) to create an [AudioPlayer](#audioplayer) instance. +Provides methods to manage and play audio. Before calling a method of **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayer) to create an **AudioPlayer** instance. -For details about the audio playback demo, see [Audio Playback Development](.../media/audio-playback.md). +For details about the audio playback demo, see [Audio Playback Development](../../media/audio-playback.md). ### Attributes -| Name| Type| Readable| Writable| Description| +| Name | Type | Readable| Writable| Description | | ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| src | string | Yes| Yes| Audio media URI. The mainstream audio formats (MP4, AAC, MP3, and OGG) are supported.
**Examples of supported URIs**:
1. Local absolute path: file:///data/data/ohos.xxx.xxx/files/test.mp4
![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)
2. HTTP network playback path (under development)
3. HLS network playback path (under development)
4. FD playback (under development)
**Precautions**:
Media files can be played only after the read permission is granted.| -| loop | boolean | Yes| Yes| Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite.| -| currentTime | number | Yes| No| Current audio playback position.| -| duration | number | Yes| No| Audio duration.| -| state | [AudioState](#audiostate) | Yes| No| Audio playback state.| +| src | string | Yes | Yes | Audio media URI. The mainstream audio formats (MP4, AAC, MP3, and OGG) are supported.
**Example of supported URIs**:
1. FD playback: fd://xxx
![en-us_image_0000001164217678](figures/en-us_image_url.png)
2. HTTP network playback path (under development)
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| currentTime | number | Yes | No | Current audio playback position.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| duration | number | Yes | No | Audio duration.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| state | [AudioState](#audiostate) | Yes | No | Audio playback state.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| ### play play(): void -Starts to play audio resources. This method can be called only after the **dataLoad** event is triggered. +Starts to play audio resources. This method can be called only after the [dataLoad](#on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange')) event is triggered. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer **Example** @@ -210,6 +296,8 @@ pause(): void Pauses audio playback. +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + **Example** ```js @@ -225,6 +313,8 @@ stop(): void Stops audio playback. +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + **Example** ```js @@ -240,6 +330,8 @@ reset(): void Switches the audio resource to be played. +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + **Example** ```js @@ -255,11 +347,13 @@ seek(timeMs: number): void Seeks to the specified playback position. +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------ | -| timeMs | number | Yes| Position to seek to, in milliseconds.| +| timeMs | number | Yes | Position to seek to, in milliseconds.| **Example** @@ -280,11 +374,13 @@ setVolume(vol: number): void Sets the volume. +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| vol | number | Yes| Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| **Example** @@ -299,7 +395,9 @@ audioPlayer.setVolume(1); // Set the volume to 100%. release(): void -Releases this **AudioPlayer** instance. +Releases the audio playback resource. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer **Example** @@ -312,13 +410,15 @@ audioPlayer = undefined; getTrackDescription(callback: AsyncCallback>): void -Obtains the audio track information. This method uses a callback to return the result. +Obtains the audio track information. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------------- | -| callback | AsyncCallback> | Yes| Callback used to return the audio track information obtained.| +| callback | AsyncCallback> | Yes | Callback used to return the audio track information obtained.| **Example** @@ -346,11 +446,13 @@ audioPlayer.getTrackDescription((error, arrlist) => { getTrackDescription(): Promise> -Obtains the audio track information. This method uses a promise to return the result. +Obtains the audio track information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer **Return value** -| Type| Description| +| Type | Description | | ------------------------------------------------------ | ------------------------------- | | Promise> | Promise used to return the audio track information obtained.| @@ -389,12 +491,14 @@ on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferingi Subscribes to the audio buffering update event. +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes| Type of the event to subscribe to, which is 'bufferingUpdate' in this example.| -| callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | Yes| Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| +| type | string | Yes | Type of the event to subscribe to, which is 'bufferingUpdate' in this example. | +| callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| **Example** @@ -411,12 +515,14 @@ on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeCh Subscribes to the audio playback events. +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ------------------------------------------------------------ | -| type | string | Yes| Type of the event to subscribe to. The following events are supported: 'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'
- The 'play' event is triggered when the [play()](#play) method is called and audio playback starts.
- The 'pause' event is triggered when the [pause()](#pause) method is called and audio playback is paused.
- The 'stop' event is triggered when the [stop()](#stop) method is called and audio playback stops.
- The 'reset' event is triggered when the [reset()](#reset7) method is called and audio playback is reset.
- The 'dataLoad' event is triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- The 'finish' event is triggered when the audio playback is finished.
- The 'volumeChange' event is triggered when the [setVolume()](#setvolume) method is called and the playback volume is changed.| -| callback | () => void | Yes| Callback invoked when the event is triggered.| +| type | string | Yes | Type of the event to subscribe to. The following events are supported: 'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'
- The 'play' event is triggered when the [play()](#play) method is called and audio playback starts.
- The 'pause' event is triggered when the [pause()](#pause) method is called and audio playback is paused.
- The 'stop' event is triggered when the [stop()](#stop) method is called and audio playback stops.
- The 'reset' event is triggered when the [reset()](#reset7) method is called and audio playback is reset.
- The 'dataLoad' event is triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- The 'finish' event is triggered when the audio playback is finished.
- The 'volumeChange' event is triggered when the [setVolume()](#setvolume) method is called and the playback volume is changed.| +| callback | () => void | Yes | Callback invoked when the event is triggered. | **Example** @@ -460,21 +566,35 @@ audioPlayer.on('error', (error) => { // Set the 'error' event callback console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errMessage is ${error.message}`); }); -audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; // Set the src attribute and trigger the 'dataLoad' event callback. + +// Set the FD (local playback) of the video file selected by the user. +let fdPath = 'fd://' +let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +await fileIO.open(path).then(fdNumber) => { + fdPath = fdPath + '' + fdNumber; + console.info('open fd sucess fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}),catch((err) => { + console.info('open fd failed err is' + err); +}); +audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. ``` ### on('timeUpdate') on(type: 'timeUpdate', callback: Callback\): void -Subscribes to the [seek()](#seek) event. +Subscribes to the 'timeUpdate' event. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | -------- | ----------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes| Type of the event to subscribe to, which is 'timeUpdate' in this method.
The 'timeUpdate' event is triggered when the [seek()](#seek) method is called.| -| callback | Callback\ | Yes| Callback invoked when the event is triggered. The input parameter of the callback is the time when the seek operation is successful.| +| type | string | Yes | Type of the event to subscribe to, which is 'timeUpdate' in this method.
The 'timeUpdate' event is triggered when the [seek()](#seek) method is called.| +| callback | Callback\ | Yes | Callback invoked when the event is triggered. The input parameter of the callback is the time when the seek operation is successful. | **Example** @@ -495,12 +615,14 @@ on(type: 'error', callback: ErrorCallback): void Subscribes to the audio playback error event. +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes| Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during audio playback.| -| callback | ErrorCallback | Yes| Callback invoked when the event is triggered.| +| type | string | Yes | Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during audio playback.| +| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** @@ -515,198 +637,1820 @@ audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'erro ## AudioState -Describes the audio playback state. You can obtain the state through the **state** attribute. +Enumerates the audio playback states. You can obtain the state through the **state** attribute. -| Name| Type| Description| -| ------------------ | ------ | -------------- | -| idle | string | Audio playback is idle.| -| playing | string | Audio playback is in progress.| -| paused | string | Audio playback is paused.| -| stopped | string | Audio playback is stopped.| -| error8+ | string | Audio playback is in the error state.| +| Name | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------ | +| idle | string | The audio player is idle.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| playing | string | Audio playback is in progress.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| paused | string | Audio playback is paused.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| stopped | string | Audio playback is stopped.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| error8+ | string | Audio playback is in the error state.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| -## MediaDescription8+ +## VideoPlayer8+ -### [key : string] : any +Provides methods to manage and play video. Before calling a method of the **VideoPlayer** class, you must call [createVideoPlayer()](#media.createvideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. -Defines media information in key-value mode. +For details about the video playback demo, see [Video Playback Development](../../media/video-playback.md). -| Name| Type| Description| -| ----- | ------ | ------------------------------------------------------------ | -| key | string | Key of the media information. For details about the keys, see [MediaDescriptionKey](#mediadescriptionkey8).| -| value | any | Value of the key. For details about the values, see [MediaDescriptionKey](#mediadescriptionkey8).| +### Attributes + +| Name | Type | Readable| Writable| Description | +| ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xxx
![en-us_image_0000001164217678](figures/en-us_image_url.png)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| currentTime8+ | number | Yes | No | Current video playback position.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| duration8+ | number | Yes | No | Video duration. The value **-1** indicates the live streaming mode.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| state8+ | [VideoPlayState](#videoplaystate8) | Yes | No | Video playback state.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| width8+ | number | Yes | No | Video width.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| height8+ | number | Yes | No | Video height.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| + +### setDisplaySurface8+ + +setDisplaySurface(surfaceId: string, callback: AsyncCallback\): void + +Sets **SurfaceId**. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------- | ---- | ------------------------- | +| surfaceId | string | Yes | Surface ID to set. | +| callback | function | Yes | Callback used to set **SurfaceId**.| **Example** ```js -function printfItemDescription(obj, key) { - let property = obj[key]; - console.info('audio key is ' + key); - console.info('audio value is ' + property); -} - -audioPlayer.getTrackDescription((error, arrlist) => { - if (typeof (arrlist) != 'undefined') { - for (let i = 0; i < arrlist.length; i++) { - printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. - } - } else { - console.log(`audio getTrackDescription fail, error:${error.message}`); +videoPlayer.setDisplaySurface(surfaceId, (err) => { + if (typeof (err) == 'undefined') { + console.info('setDisplaySurface success!'); + } else { + console.info('setDisplaySurface fail!'); } }); ``` -## AudioRecorder +### setDisplaySurface8+ -Implements audio recording. Before calling a method of the **AudioRecorder** class, you must call [createAudioRecorder()](#mediacreateaudiorecorder) to create an **AudioRecorder** instance. +setDisplaySurface(surfaceId: string): Promise\ -### prepare +Sets **SurfaceId**. This API uses a promise to return the result. -prepare(config: AudioRecorderConfig): void +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -Prepares for recording. +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | --------- | +| surfaceId | string | Yes | Surface ID to set.| + +**Return value** + +| Type | Description | +| ------------- | ------------------------------ | +| Promise | Promise used to set **SurfaceId**.| + +**Example** + +```js +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); +} +await videoPlayer.setDisplaySurface(surfaceId).then(() => { + console.info('setDisplaySurface success'); +}, failureCallback).catch(catchCallback); +``` + +### prepare8+ + +prepare(callback: AsyncCallback\): void + +Prepares for video playback. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer **Parameters** -| Name| Type| Mandatory| Description| -| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes| Recording parameters, including the audio output URI, encoding format, sampling rate, and number of audio channels.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------ | +| callback | function | Yes | Callback used to return the result.| **Example** +```js +videoPlayer.prepare((err) => { + if (typeof (err) == 'undefined') { + console.info('prepare success!'); + } else { + console.info('prepare fail!'); + } +}); ``` -var audiorecorder = media.createAudioRecorder(); -let audioRecorderConfig = { - audioEncoder : AAC_LC , - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : AAC_ADTS, - uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', + +### prepare8+ + +prepare(): Promise\ + +Prepares for video playback. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); } -audiorecorder.prepare(audioRecorderConfig) +await videoPlayer.prepare().then(() => { + console.info('prepare success'); +}, failureCallback).catch(catchCallback); ``` +### play8+ -### start +play(callback: AsyncCallback\): void; -start(): void +Starts to play video resources. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -Starts audio recording. +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------ | +| callback | function | Yes | Callback used to return the result.| **Example** +```js +videoPlayer.play((err) => { + if (typeof (err) == 'undefined') { + console.info('play success!'); + } else { + console.info('play fail!'); + } +}); ``` -var audiorecorder = media.createAudioRecorder(); -audiorecorder.start(); + +### play8+ + +play(): Promise\; + +Starts to play video resources. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); +} +await videoPlayer.play().then(() => { + console.info('play success'); +}, failureCallback).catch(catchCallback); ``` -### stop +### pause8+ -stop(): void +pause(callback: AsyncCallback\): void -Stops audio recording. +Pauses video playback. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------ | +| callback | function | Yes | Callback used to return the result.| **Example** +```js +videoPlayer.pause((err) => { + if (typeof (err) == 'undefined') { + console.info('pause success!'); + } else { + console.info('pause fail!'); + } +}); ``` -var audiorecorder = media.createAudioRecorder(); -audiorecorder.stop(); + +### pause8+ + +pause(): Promise\ + +Pauses video playback. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); +} +await videoPlayer.pause().then(() => { + console.info('pause success'); +}, failureCallback).catch(catchCallback); ``` -### release +### stop8+ -release(): void +stop(callback: AsyncCallback\): void + +Stops video playback. This API uses a callback to return the result. -Releases this **AudioRecorder** instance. +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------ | +| callback | function | Yes | Callback used to return the result.| **Example** +```js +videoPlayer.stop((err) => { + if (typeof (err) == 'undefined') { + console.info('stop success!'); + } else { + console.info('stop fail!'); + } +}); ``` -var audiorecorder = media.createAudioRecorder(); -audiorecorder.release(); + +### stop8+ + +stop(): Promise\ + +Stops video playback. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); +} +await videoPlayer.stop().then(() => { + console.info('stop success'); +}, failureCallback).catch(catchCallback); ``` -### reset +### reset8+ -reset(): void +reset(callback: AsyncCallback\): void -Resets audio recording. +Switches the video resource to be played. This API uses a callback to return the result. -Before resetting audio recording, you must call **stop()** to stop recording. After audio recording is reset, you must call **prepare()** to set the recording configurations for another recording. +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------ | +| callback | function | Yes | Callback used to return the result.| **Example** +```js +videoPlayer.reset((err) => { + if (typeof (err) == 'undefined') { + console.info('reset success!'); + } else { + console.info('reset fail!'); + } +}); ``` -var audiorecorder = media.createAudioRecorder(); -audiorecorder.reset(); + +### reset8+ + +reset(): Promise\ + +Switches the video resource to be played. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); +} +await videoPlayer.reset().then(() => { + console.info('reset success'); +}, failureCallback).catch(catchCallback); ``` -### on('prepare' | 'start' | 'stop' | 'release' | 'reset') +### seek8+ -on(type: 'prepare' | 'start' | 'stop' | 'release' | 'reset', callback: () => void): void +seek(timeMs: number, callback: AsyncCallback\): void -Subscribes to the audio recording events. +Seeks to the specified playback position. The next key frame at the specified position is played. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes| Type of the event to subscribe to. The following events are supported: 'prepare'\|'start'\|'stop'\|'release'\|'reset'
- The 'prepare' event is triggered when audio recording preparation is complete.
- The 'start' event is triggered when audio recording starts.
- The 'stop' event is triggered when audio recording is stopped.
- The 'release' event is triggered when the resources related to audio recording are released.
- The 'reset' event is triggered when audio recording is reset.| -| callback | function | Yes| Callback invoked when the event is triggered.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------ | +| timeMs | number | Yes | Position to seek to, in milliseconds.| +| callback | function | Yes | Callback used to return the result.| **Example** -``` -var audiorecorder = media.createAudioRecorder(); -audiorecorder.on('prepare', () => { - console.log('Preparation succeeded.'); - audiorecorder.start(); +```js +videoPlayer.seek((seekTime, err) => { + if (typeof (err) == 'undefined') { + console.info('seek success!'); + } else { + console.info('seek fail!'); + } }); ``` -### on('error') +### seek8+ -on(type: 'error', callback: ErrorCallback): void +seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\): void -Subscribes to the audio recording error event. +Seeks to the specified playback position. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer **Parameters** -| Name| Type| Mandatory| Description| -| -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes| Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during audio recording.| -| callback | ErrorCallback | Yes| Callback invoked when the event is triggered.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ---------------------------------------- | +| timeMs | number | Yes | Position to seek to, in milliseconds. | +| mode | SeekMode | Yes | Seek mode. For details, see [SeekMode](#seekmode8).| +| callback | function | Yes | Callback used to return the result. | +**Example** -## AudioRecorderConfig +```js +videoPlayer.seek((seekTime, seekMode, err) => { + if (typeof (err) == 'undefined') { + console.info('seek success!'); + } else { + console.info('seek fail!'); + } +}); +``` -Describes audio recording configurations. +### seek8+ -| Name| Type| Mandatory| Description| -| ------------------ | --------------------------------------- | ---- | ------------------------------------------------------------ | -| audioEncoder | [AudioEncoder](#audioencoder) | No| Audio encoding format. The default value is **AAC_LC**.| -| audioEncodeBitRate | number | No| Audio encoding bit rate. The default value is **48000**.| -| audioSampleRate | number | No| Audio sampling rate. The default value is **48000**.| -| numberOfChannels | number | No| Number of audio channels. The default value is **2**.| -| format | [AudioOutputFormat](#audiooutputformat) | No| Audio output format. The default value is **MPEG_4**.| -| uri | string | Yes| Audio output URI. The following URI types are supported:
1. Absolute file path: file:///data/data/ohos.xxx.xxx/cache/test.mp4![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)
2. FD path: file://1 (fd number)| +seek(timeMs: number, mode?:SeekMode): Promise\ +Seeks to the specified playback position. If **mode** is not specified, the next key frame at the specified position is played. This API uses a promise to return the result. -## AudioEncoder +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -Enumerates the audio encoding formats. +**Parameters** -| Name| Default Value| Description| -| ------ | ------ | ------------------------------------------------------------ | -| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------------------------- | +| timeMs | number | Yes | Position to seek to, in milliseconds. | +| mode | SeekMode | No | Seek mode. For details, see [SeekMode](#seekmode8).| +**Return value** -## AudioOutputFormat +| Type | Description | +| -------------- | ----------------------------------- | +| Promise\ | Promise used to return the result.| -Enumerates the audio output formats. +**Example** -| Name| Default Value| Description| -| -------- | ------ | ------------------------------------------------------------ | -| MPEG_4 | 2 | MPEG-4.| -| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| +```js +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); +} +await videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime indicates the position after the seek operation is complete. + console.info('seek success'); +}, failureCallback).catch(catchCallback); + +await videoPlayer.seek(seekTime, seekMode).then((seekDoneTime) => { + console.info('seek success'); +}, failureCallback).catch(catchCallback); +``` + +### setVolume8+ + +setVolume(vol: number, callback: AsyncCallback\): void + +Sets the volume. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| +| callback | function | Yes | Callback used to return the result. | + +**Example** + +```js +videoPlayer.setVolume((vol, err) => { + if (typeof (err) == 'undefined') { + console.info('setVolume success!'); + } else { + console.info('setVolume fail!'); + } +}); +``` + +### setVolume8+ + +setVolume(vol: number): Promise\ + +Sets the volume. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| + +**Return value** + +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); +} +await videoPlayer.setVolume(vol).then() => { + console.info('setVolume success'); +}, failureCallback).catch(catchCallback); +``` + +### release8+ + +release(callback: AsyncCallback\): void + +Releases the video playback resource. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------ | +| callback | function | Yes | Callback used to return the result.| + +**Example** + +```js +videoPlayer.release((err) => { + if (typeof (err) == 'undefined') { + console.info('release success!'); + } else { + console.info('release fail!'); + } +}); +``` + +### release8+ + +release(): Promise\ + +Releases the video playback resource. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); +} +await videoPlayer.release().then() => { + console.info('release success'); +}, failureCallback).catch(catchCallback); +``` + +### getTrackDescription8+ + +getTrackDescription(callback: AsyncCallback>)>>): void + +Obtains the video track information. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | -------------------------- | +| callback | function | Yes | Callback used to return the video track information obtained.| + +**Example** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('video key is ' + item); + console.info('video value is ' + property); + } +} + +videoPlayer.getTrackDescription((error, arrlist) => { + if (typeof (arrlist) != 'undefined') { + for (let i = 0; i < arrlist.length; i++) { + printfDescription(arrlist[i]); + } + } else { + console.log(`video getTrackDescription fail, error:${error.message}`); + } +}); +``` + +### getTrackDescription8+ + +getTrackDescription(): Promise>)>> + +Obtains the video track information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------------------------------------------------- | ------------------------------- | +| Promise>)>> | Promise used to return the video track information obtained.| + +**Example** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('video key is ' + item); + console.info('video value is ' + property); + } +} +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); +} + +let arrayDescription; +await videoPlayer.getTrackDescription().then((arrlist) => { + if (typeof (arrlist) != 'undefined') { + arrayDescription = arrlist; + } else { + console.log('video getTrackDescription fail'); + } +}, failureCallback).catch(catchCallback); +for (let i = 0; i < arrayDescription.length; i++) { + printfDescription(arrayDescription[i]); +} +``` + +### setSpeed8+ + +setSpeed(speed:number, callback: AsyncCallback\): void + +Sets the video playback speed. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ---------------------------------------------------------- | +| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| +| callback | function | Yes | Callback used to return the result. | + +**Example** + +```js +videoPlayer.setSpeed((speed:number, err) => { + if (typeof (err) == 'undefined') { + console.info('setSpeed success!'); + } else { + console.info('setSpeed fail!'); + } +}); +``` + +### setSpeed8+ + +setSpeed(speed:number): Promise\ + +Sets the video playback speed. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------------------------------------- | +| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| + +**Example** + +```js +function failureCallback(error) { + console.info(`video failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`video catchCallback, error:${error.message}`); +} +await videoPlayer.setSpeed(speed).then() => { + console.info('setSpeed success'); +}, failureCallback).catch(catchCallback); +``` + +### on('playbackCompleted')8+ + +on(type: 'playbackCompleted', callback: Callback\): void + +Subscribes to the video playback completion event. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ----------------------------------------------------------- | +| type | string | Yes | Type of the event to subscribe to, which is 'playbackCompleted' in this example.| +| callback | function | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +videoPlayer.on('playbackCompleted', () => { + console.info('playbackCompleted success!'); +}); +``` + +### on('bufferingUpdate')8+ + +on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void + +Subscribes to the video buffering update event. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of the event to subscribe to, which is 'bufferingUpdate' in this example. | +| callback | function | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| + +**Example** + +```js +videoPlayer.on('bufferingUpdate', (infoType, value) => { + console.log('video bufferingInfo type: ' + infoType); + console.log('video bufferingInfo value: ' + value); +}); +``` + +### on('startRenderFrame')8+ + +on(type: 'startRenderFrame', callback: Callback\): void + +Subscribes to the frame rendering start event. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of the event to subscribe to, which is 'startRenderFrame' in this example.| +| callback | function | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +videoPlayer.on('startRenderFrame', () => { + console.info('startRenderFrame success!'); +}); +``` + +### on('videoSizeChanged')8+ + +on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void + +Subscribes to the video width and height change event. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of the event to subscribe to, which is 'videoSizeChanged' in this example.| +| callback | function | Yes | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height. | + +**Example** + +```js +videoPlayer.on('videoSizeChanged', (width, height) => { + console.log('video width is: ' + width); + console.log('video height is: ' + height); +}); +``` + +### on('error')8+ + +on(type: 'error', callback: ErrorCallback): void + +Subscribes to the video playback error event. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during video playback.| +| callback | function | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +videoPlayer.on('error', (error) => { // Set the 'error' event callback. + console.info(`video error called, errName is ${error.name}`); // Print the error name. + console.info(`video error called, errCode is ${error.code}`); // Print the error code. + console.info(`video error called, errMessage is ${error.message}`);// Print the detailed description of the error type. +}); +videoPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. +``` + +## VideoPlayState8+ + +Enumerates the video playback states. You can obtain the state through the **state** attribute. + +| Name | Type | Description | +| -------- | ------ | ------------------------------------------------------------ | +| idle | string | The video player is idle.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| prepared | string | Video playback is being prepared.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| playing | string | Video playback is in progress.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| paused | string | Video playback is paused.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| stopped | string | Video playback is stopped.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| error | string | Video playback is in the error state.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| + +## SeekMode8+ + +Enumerates the video playback seek modes, which can be passed in the **seek** method. + +| Name | Value | Description | +| -------------- | ---- | ------------------------------------------------------------ | +| SEEK_NEXT_SYNC | 0 | Seeks to the next key frame at the specified position. You are advised to use this value for the rewind operation.
**System capability**: SystemCapability.Multimedia.Media.Core| +| SEEK_PREV_SYNC | 1 | Seeks to the previous key frame at the specified position. You are advised to use this value for the fast-forward operation.
**System capability**: SystemCapability.Multimedia.Media.Core| + +## PlaybackSpeed8+ + +Enumerates the video playback speeds, which can be passed in the **setSpeed** method. + +| Name | Value | Description | +| -------------------- | ---- | ------------------------------------------------------------ | +| SPEED_FORWARD_0_75_X | 0 | Plays the video at 0.75 times the normal speed.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| SPEED_FORWARD_1_00_X | 1 | Plays the video at the normal speed.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| SPEED_FORWARD_1_25_X | 2 | Plays the video at 1.25 times the normal speed.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| SPEED_FORWARD_1_75_X | 3 | Plays the video at 1.75 times the normal speed.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| SPEED_FORWARD_2_00_X | 4 | Plays the video at 2.00 times the normal speed.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| + +## MediaDescription8+ + +### [key : string] : any + +Defines media information in key-value mode. + +| Name | Type | Description | +| ----- | ------ | ------------------------------------------------------------ | +| key | string | Key of the media information. For details about the keys, see [MediaDescriptionKey](#mediadescriptionkey8).
**System capability**: SystemCapability.Multimedia.Media.Core| +| value | any | Value of the key. For details about the values, see [MediaDescriptionKey](#mediadescriptionkey8).
**System capability**: SystemCapability.Multimedia.Media.Core| + +**Example** + +```js +function printfItemDescription(obj, key) { + let property = obj[key]; + console.info('audio key is ' + key); + console.info('audio value is ' + property); +} + +audioPlayer.getTrackDescription((error, arrlist) => { + if (typeof (arrlist) != 'undefined') { + for (let i = 0; i < arrlist.length; i++) { + printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. + } + } else { + console.log(`audio getTrackDescription fail, error:${error.message}`); + } +}); +``` + +## AudioRecorder + +Implements audio recording. Before calling a method of the **AudioRecorder** class, you must call [createAudioRecorder()](#media.createaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. + +For details about the audio recording demo, see [Audio Recording Development](../../media/audio-recorder.md). + +### prepare + +prepare(config: AudioRecorderConfig): void + +Prepares for recording. + +**Required permissions:** ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Audio recording parameters, including the audio output URI, [encoding format](#audioencoder), sampling rate, number of audio channels, and [output format](#audiooutputformat).| + +**Example** + +```js +let audioRecorderConfig = { + audioEncoder : media.AudioEncoder.AAC_LC, + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://1', // The file must be created by the caller and granted with proper permissions. + location : { latitude : 30, longitude : 130}, +} +audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. + console.log('prepare success'); +}); +audioRecorder.prepare(audioRecorderConfig); +``` + + +### start + +start(): void + +Starts audio recording. This method can be called only after the [prepare](#audiorecorder_on) event is triggered. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('start', () => { // Set the 'start' event callback. + console.log('audio recorder start success'); +}); +audioRecorder.start(); +``` + +### pause + +pause():void + +Pauses audio recording. This method can be called only after the [start](#audiorecorder_on) event is triggered. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('pause', () => { // Set the 'pause' event callback. + console.log('audio recorder pause success'); +}); +audioRecorder.pause(); +``` + +### resume + +resume():void + +Resumes audio recording. This method can be called only after the [pause](#audiorecorder_on) event is triggered. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('resume', () => { // Set the 'resume' event callback. + console.log('audio recorder resume success'); +}); +audioRecorder.resume(); +``` + +### stop + +stop(): void + +Stops audio recording. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('stop', () => { // Set the 'stop' event callback. + console.log('audio recorder stop success'); +}); +audioRecorder.stop(); +``` + +### release + +release(): void + +Releases the audio recording resource. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('release', () => { // Set the 'release' event callback. + console.log('audio recorder release success'); +}); +audioRecorder.release(); +audioRecorder = undefined; +``` + +### reset + +reset(): void + +Resets audio recording. + +Before resetting audio recording, you must call [stop()](#audiorecorder_stop) to stop recording. After audio recording is reset, you must call [prepare()](#audiorecorder_prepare) to set the recording parameters for another recording. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('reset', () => { // Set the 'reset' event callback. + console.log('audio recorder reset success'); +}); +audioRecorder.reset(); +``` + +### on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset') + +on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void + +Subscribes to the audio recording events. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of the event to subscribe to. The following events are supported: 'prepare'\|'start'\| 'pause' \| 'resume' \|'stop'\|'release'\|'reset'
- The 'prepare' event is triggered when the [prepare](#audiorecorder_prepare) method is called and the audio recording parameters are set.
- The 'start' event is triggered when the [start](#audiorecorder_start) method is called and audio recording starts.
- The 'pause' event is triggered when the [pause](#audiorecorder_pause) method is called and audio recording is paused.
- The 'resume' event is triggered when the [resume](#audiorecorder_resume) method is called and audio recording is resumed.
- The 'stop' event is triggered when the [stop](#audiorecorder_stop) method is called and audio recording stops.
- The 'release' event is triggered when the [release](#audiorecorder_release) method is called and the recording resource is released.
- The 'reset' event is triggered when the [reset](#audiorecorder_reset) method is called and audio recording is reset.| +| callback | ()=>void | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +let audiorecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. +let audioRecorderConfig = { + audioEncoder : media.AudioEncoder.AAC_LC, , + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + location : { latitude : 30, longitude : 130}, +} +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}`); +}); +audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. + console.log('prepare success'); + audioRecorder.start(); // Start recording and trigger the 'start' event callback. +}); +audioRecorder.on('start', () => { // Set the 'start' event callback. + console.log('audio recorder start success'); +}); +audioRecorder.on('pause', () => { // Set the 'pause' event callback. + console.log('audio recorder pause success'); +}); +audioRecorder.on('resume', () => { // Set the 'resume' event callback. + console.log('audio recorder resume success'); +}); +audioRecorder.on('stop', () => { // Set the 'stop' event callback. + console.log('audio recorder stop success'); +}); +audioRecorder.on('release', () => { // Set the 'release' event callback. + console.log('audio recorder release success'); +}); +audioRecorder.on('reset', () => { // Set the 'reset' event callback. + console.log('audio recorder reset success'); +}); +audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +Subscribes to the audio recording error event. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during audio recording.| +| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +audioRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); // Print the error name. + console.info(`audio error called, errCode is ${error.code}`); // Print the error code. + console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. +}); +audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. +``` + +## AudioRecorderConfig + +Describes audio recording configurations. + +| Name | Type | Mandatory| Description | +| --------------------- | --------------------------------------- | ---- | ------------------------------------------------------------ | +| audioEncoder | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| audioEncodeBitRate | number | No | Audio encoding bit rate. The default value is **48000**.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| audioSampleRate | number | No | Audio sampling rate. The default value is **48000**.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| numberOfChannels | number | No | Number of audio channels. The default value is **2**.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| format | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| location8+ | [Location](#location8) | No | Geographical location of the recorded audio.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| + + +## AudioEncoder + +Enumerates the audio encoding formats. + +| Name | Default Value| Description | +| ------- | ------ | ------------------------------------------------------------ | +| DEFAULT | 0 | Default audio encoding format, which is Adaptive Multi Rate-Narrow Band Speech Codec (AMR-NB).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AMR_NB | 1 | AMR-NB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| + + +## AudioOutputFormat + +Enumerates the audio output formats. + +| Name | Default Value| Description | +| -------- | ------ | ------------------------------------------------------------ | +| DEFAULT | 0 | Default encapsulation format, which is MPEG-4.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| MPEG_4 | 2 | MPEG-4.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AMR_NB | 3 | AMR_NB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AMR_WB | 4 | AMR_WB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| + +## VideoRecorder8+ + +Implements video recording. Before calling a method of the **VideoRecorder** class, you must call [createVideoRecorder()](#media.createvideorecorder8) to create a [VideoRecorder](#videorecorder8) instance. + +For details about the video recording demo, see [Video Recording Development](../../media/video-recorder.md). + +### Attributes + +| Name | Type | Readable| Writable| Description | +| ------------------ | ------------------------------------- | ---- | ---- | ---------------- | +| state8+ | [VideoRecordState](#videorecordstate) | Yes | No | Video recording state.| + +### prepare8+ + +prepare(config: VideoRecorderConfig, callback: AsyncCallback\): void; + +Sets video recording parameters in asynchronous mode. This API uses a callback to return the result. + +**Required permissions:** ohos.permission.MICROPHONE ohos.permission.CAMERA + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| config | [VideoRecorderConfig](#videorecorderconfig) | Yes | Video recording parameters to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let videoProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : 'audio/mp4a-latm', + audioSampleRate : 48000, + fileFormat : 'mp4', + videoBitrate : 48000, + videoCodec : 'video/mp4v-es', + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 +} + +let videoConfig = { + audioSourceType : 1, + videoSourceType : 0, + profile : videoProfile, + url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + orientationHint : 0, + location : { latitude : 30, longitude : 130 }, +} + +// asyncallback +let videoRecorder = null; +let events = require('events'); +let eventEmitter = new events.EventEmitter(); + +eventEmitter.on('prepare', () => { + videoRecorder.prepare(videoConfig, (err) => { + if (typeof (err) == 'undefined') { + console.info('prepare success'); + } else { + console.info('prepare failed and error is ' + err.message); + } + }); +}); + +media.createVideoRecorder((err, recorder) => { + if (typeof (err) == 'undefined' && typeof (recorder) != 'undefined') { + videoRecorder = recorder; + console.info('createVideoRecorder success'); + eventEmitter.emit('prepare'); // Trigger the 'prepare' event. + } else { + console.info('createVideoRecorder failed and error is ' + err.message); + } +}); +``` + +### prepare8+ + +prepare(config: VideoRecorderConfig): Promise\; + +Sets video recording parameters in asynchronous mode. This API uses a promise to return the result. + +**Required permissions:** ohos.permission.MICROPHONE ohos.permission.CAMERA + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------- | ---- | ------------------------ | +| config | [VideoRecorderConfig](#videorecorderconfig) | Yes | Video recording parameters to set.| + +**Return value** + +| Type | Description | +| -------------- | ---------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let videoProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : 'audio/mp4a-latm', + audioSampleRate : 48000, + fileFormat : 'mp4', + videoBitrate : 48000, + videoCodec : 'video/mp4v-es', + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 +} + +let videoConfig = { + audioSourceType : 1, + videoSourceType : 0, + profile : videoProfile, + url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + orientationHint : 0, + location : { latitude : 30, longitude : 130 }, +} + +// promise +let videoRecorder = null; +await media.createVideoRecorder().then((recorder) => { + if (typeof (recorder) != 'undefined') { + videoRecorder = recorder; + console.info('createVideoRecorder success'); + } else { + console.info('createVideoRecorder failed'); + } +}, (err) => { + console.info('error hanppend message is ' + err.message); +}).catch((err) => { + console.info('catch err error message is ' + err.message); +}); + +await videoRecorder.prepare(videoConfig).then(() => { + console.info('prepare success'); +}, (err) => { + console.info('prepare failed and error is ' + err.message); +}).catch((err) => { + console.info('prepare failed and catch error is ' + err.message); +}); +``` + +### getInputSurface8+ + +getInputSurface(callback: AsyncCallback\): void; + +Obtains the surface required for recording in asynchronous mode. This surface is provided for the caller. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data. + +Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp is based on the system startup time. + +This method can be called only after [prepare()](#videorecorder_prepare1) is called. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | --------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to obtain the result.| + +**Example** + +```js +// asyncallback +let surfaceID = null; // Surface ID passed to the external system. +videoRecorder.getInputSurface((err, surfaceId) => { + if (typeof (err) == 'undefined') { + console.info('getInputSurface success'); + surfaceID = surfaceId; + } else { + console.info('getInputSurface failed and error is ' + err.message); + } +}); +``` + +### getInputSurface8+ + +getInputSurface(): Promise\; + + Obtains the surface required for recording in asynchronous mode. This surface is provided for the caller. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data. + +Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp is based on the system startup time. + +This method can be called only after [prepare()](#videorecorder_prepare1) is called. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Return value** + +| Type | Description | +| ---------------- | -------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +// promise +let surfaceID = null; // Surface ID passed to the external system. +await videoRecorder.getInputSurface().then((surfaceId) => { + console.info('getInputSurface success'); + surfaceID = surfaceId; +}, (err) => { + console.info('getInputSurface failed and error is ' + err.message); +}).catch((err) => { + console.info('getInputSurface failed and catch error is ' + err.message); +}); +``` + +### start8+ + +start(callback: AsyncCallback\): void; + +Starts video recording in asynchronous mode. This API uses a callback to return the result. + +This method can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +// asyncallback +videoRecorder.start((err) => { + if (typeof (err) == 'undefined') { + console.info('start videorecorder success'); + } else { + console.info('start videorecorder failed and error is ' + err.message); + } +}); +``` + +### start8+ + +start(): Promise\; + +Starts video recording in asynchronous mode. This API uses a promise to return the result. + +This method can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +// promise +await videoRecorder.start().then(() => { + console.info('start videorecorder success'); +}, (err) => { + console.info('start videorecorder failed and error is ' + err.message); +}).catch((err) => { + console.info('start videorecorder failed and catch error is ' + err.message); +}); +``` + +### pause8+ + +pause(callback: AsyncCallback\): void; + +Pauses video recording in asynchronous mode. This API uses a callback to return the result. + +This method can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +// asyncallback +videoRecorder.pause((err) => { + if (typeof (err) == 'undefined') { + console.info('pause videorecorder success'); + } else { + console.info('pause videorecorder failed and error is ' + err.message); + } +}); +``` + +### pause8+ + +pause(): Promise\; + +Pauses video recording in asynchronous mode. This API uses a promise to return the result. + +This method can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +// promise +await videoRecorder.pause().then(() => { + console.info('pause videorecorder success'); +}, (err) => { + console.info('pause videorecorder failed and error is ' + err.message); +}).catch((err) => { + console.info('pause videorecorder failed and catch error is ' + err.message); +}); +``` + +### resume8+ + +resume(callback: AsyncCallback\): void; + +Resumes video recording in asynchronous mode. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +// asyncallback +videoRecorder.resume((err) => { + if (typeof (err) == 'undefined') { + console.info('resume videorecorder success'); + } else { + console.info('resume videorecorder failed and error is ' + err.message); + } +}); +``` + +### resume8+ + +resume(): Promise\; + +Resumes video recording in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +// promise +await videoRecorder.resume().then(() => { + console.info('resume videorecorder success'); +}, (err) => { + console.info('resume videorecorder failed and error is ' + err.message); +}).catch((err) => { + console.info('resume videorecorder failed and catch error is ' + err.message); +}); +``` + +### stop8+ + +stop(callback: AsyncCallback\): void; + +Stops video recording in asynchronous mode. This API uses a callback to return the result. + +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +// asyncallback +videoRecorder.stop((err) => { + if (typeof (err) == 'undefined') { + console.info('stop videorecorder success'); + } else { + console.info('stop videorecorder failed and error is ' + err.message); + } +}); +``` + +### stop8+ + +stop(): Promise\; + +Stops video recording in asynchronous mode. This API uses a promise to return the result. + +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +// promise +await videoRecorder.stop().then(() => { + console.info('stop videorecorder success'); +}, (err) => { + console.info('stop videorecorder failed and error is ' + err.message); +}).catch((err) => { + console.info('stop videorecorder failed and catch error is ' + err.message); +}); +``` + +### release8+ + +release(callback: AsyncCallback\): void; + +Releases the video recording resource in asynchronous mode. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +// asyncallback +videoRecorder.release((err) => { + if (typeof (err) == 'undefined') { + console.info('release videorecorder success'); + } else { + console.info('release videorecorder failed and error is ' + err.message); + } +}); +``` + +### release8+ + +release(): Promise\; + +Releases the video recording resource in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Return value** + +| Type | Description | +| -------------- | ----------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +// promise +await videoRecorder.release().then(() => { + console.info('release videorecorder success'); +}, (err) => { + console.info('release videorecorder failed and error is ' + err.message); +}).catch((err) => { + console.info('release videorecorder failed and catch error is ' + err.message); +}); +``` + +### reset8+ + +reset(callback: AsyncCallback\): void; + +Resets video recording in asynchronous mode. This API uses a callback to return the result. + +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +// asyncallback +videoRecorder.reset((err) => { + if (typeof (err) == 'undefined') { + console.info('reset videorecorder success'); + } else { + console.info('reset videorecorder failed and error is ' + err.message); + } +}); +``` + +### reset8+ + +reset(): Promise\; + +Resets video recording in asynchronous mode. This API uses a promise to return the result. + +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +// promise +await videoRecorder.reset().then(() => { + console.info('reset videorecorder success'); +}, (err) => { + console.info('reset videorecorder failed and error is ' + err.message); +}).catch((err) => { + console.info('reset videorecorder failed and catch error is ' + err.message); +}); +``` + +### on('error')8+ + +on(type: 'error', callback: ErrorCallback): void + +Subscribes to the video recording error event. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during video recording.| +| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +videoRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); // Print the error name. + console.info(`audio error called, errCode is ${error.code}`); // Print the error code. + console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. +}); +// This event is reported when an error occurs during the retrieval of videoRecordState. +``` + +## VideoRecordState8+ + +Enumerates the video recording states. You can obtain the state through the **state** attribute. + +| Name | Type | Description | +| -------- | ------ | ------------------------------------------------------------ | +| idle | string | The video recorder is idle.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| prepared | string | The video recording parameters are set.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| playing | string | Video recording is in progress.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| paused | string | Video recording is paused.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| stopped | string | Video recording is stopped.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| error | string | Video recording is in the error state.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| + +## VideoRecorderConfig8+ + +Describes the video recording parameters. + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| audioSourceType | [AudioSourceType](#audiosourcetype8+) | Yes | Type of the audio source for video recording.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| videoSourceType | [VideoSourceType](#videosourcetype8+) | Yes | Type of the video source for video recording.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| profile | [VideoRecorderProfile](#videorecorderprofile8+) | Yes | Video recording profile.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| orientationHint | number | No | Rotation angle of the recorded video.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| location | [Location](#location8) | No | Geographical location of the recorded video.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| + +## AudioSourceType8+ + +Enumerates the audio source types for video recording. + +| Name | Value | Description | +| ------------------------- | ---- | ------------------------------------------------------------ | +| AUDIO_SOURCE_TYPE_DEFAULT | 0 | Default audio input source.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| AUDIO_SOURCE_TYPE_MIC | 1 | Mic audio input source.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| + +## VideoSourceType8+ + +Enumerates the video source types for video recording. + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | The input surface carries raw data.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | The input surface carries ES data.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| + +## VideoRecorderProfile8+ + +Describes the video recording profile. + +| Name | Type | Mandatory| Description | +| ---------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| audioBitrate | number | Yes | Audio encoding bit rate.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| audioChannels | number | Yes | Number of audio channels.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| audioCodec | [CodecMimeType](#CodecMimeType8) | Yes | Audio encoding format.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| audioSampleRate | number | Yes | Audio sampling rate.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| fileFormat | [ContainerFormatType](#containerformattype8) | Yes | Container format of a file.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| videoCodec | [CodecMimeType](#CodecMimeType8) | Yes | Video encoding format.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| videoFrameWidth | number | Yes | Width of the recorded video frame.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| videoFrameHeight | number | Yes | Height of the recorded video frame.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| + +## ContainerFormatType8+ + +Enumerates the container format types (CFTs). + +| Name | Value | Description | +| ----------- | ----- | ------------------------------------------------------------ | +| CFT_MPEG_4 | "mp4" | Video container format MP4.
**System capability**: SystemCapability.Multimedia.Media.Core| +| CFT_MPEG_4A | "m4a" | Audio container format M4A.
**System capability**: SystemCapability.Multimedia.Media.Core| + +## Location8+ + +Describes the geographical location of the recorded video. + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ------------------------------------------------------------ | +| latitude | number | Yes | Latitude of the geographical location.
**System capability**: SystemCapability.Multimedia.Media.Core| +| longitude | number | Yes | Longitude of the geographical location.
**System capability**: SystemCapability.Multimedia.Media.Core| -- Gitee From d2a1c33f32ab11fe8723e1f466d5323d36a47463 Mon Sep 17 00:00:00 2001 From: wusongqing Date: Wed, 16 Mar 2022 17:26:57 +0800 Subject: [PATCH 2/4] updated docs Signed-off-by: wusongqing --- .../reference/apis/figures/en-us_image_url.png | Bin 0 -> 2303 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 en/application-dev/reference/apis/figures/en-us_image_url.png diff --git a/en/application-dev/reference/apis/figures/en-us_image_url.png b/en/application-dev/reference/apis/figures/en-us_image_url.png new file mode 100644 index 0000000000000000000000000000000000000000..b134ebc1d7df208e53209f77ffeffb0f3d5ffca4 GIT binary patch literal 2303 zcmai0XHXLg5{}ZPBPB@HhjgiV2mz!TN)RNJ(4+(jsPv8j6oH`hB2ttl@Bryu3FS$P zB7~9oDxw{{CKfZ5gXLe_HclO)a7k5n!ST9|<1ONb7jSTf+=eF@2 zwv6=W9Q1{U@7!DnfEnllYH)&U=MJsA&K(^9pgx89)P?TcXYw_)4FCYxdVk|WrVN_^ z0KoXtNMFY?)Nw1%$wLq;gzai@!}O6Ygg#Y_aQPiuz(uD=z-l>SrMhZH?EXxKVg7U5 zy0y!u*&}>c%f#iYrNEs?;* z)?!OQkLgQ-_St0WLYpJSgus}TeX}%GLLp*@Q&{t@7xL~aP~t;6c8>{x5JRGj*7{5F zA0o7!MMf5LJJW z0a|XcBC>t$cNlvhzdJBNhgG&6s#x(rb*2{vlf-8#`4MkJ%zMY0ogcgIDJgZ$T2?%@ z+?m&F>(%eD4<4RC>kMXl^GzscWVf4S&>#>lXyZ-VW@a^G!VO3mdQp&K%)Iocl+$BZ znXGp7!2p7J)%?zm(~evFevs>*W%(1r!?NY~Y?x}@tsO5@@$ZdvUh^1-z!F0O+MG(C zne#M4$Gf?QRM&ERX$Drd(YxITz2X>@^Yz}zWaW-Epj z2_!Y=3lrqpW7Lu2$0#<*<}oE+qhnW`8&_@kkmQ}QH_>D&p1G!ymse-2+hnz`y*{jt z!A@z`XEwb6-f8_(+y(rV$sxj>BU+g`P%JR_qg)>Sc|#sMJkxw{nt`DD=JTqq%(cTnw`a_{Ia*M*xl{F zdAxi4VdtIYd&~s_ybu#gB4_{ zpW$5wLl|DTfiUESXZWK&e%pa)Gt&VOeA*3^FopbZl!dyT_{QSbKs zoX7d6D>>llBzR=@i-X$6uCq}q&&Xds?Ue4rT`aa>UZNiEd-z#vG-CPn5munf+&WRD z*oVqLzP=K=HP3uxv8MP_c@yni(35h^YD+Vp8y4g3~`?pDMW zT)Iz#J?q;qAXKEi1~wXfMieY&O=DLE_CNbyV;uo1!jXz2M6^oQjeAW4c#gQF;^%>1 z0Z19?Fhg!UnG9-UHTmN~p}VO|pMvNu$>~=69!u_F#L#;>Kj4jc8)>oBxrS-{qDrV* zR8KHloIkZEu7^cSn%x{C(zYNy6qCFBe2R#dX`}%;eC?*OC8DG9SV&hj&_5A&OZZog zupDno1$FJ9!Rf8>O#KL&2PF)f6Co8AlR-;$$rmA#TAG*w6@}`;D1?gBadK!clIasf z1B1>afcs8#taeF5@kmpVLnabS2ss&X?t=ix#0dLi_6 z(eNc$Y+CLlacxja#&fsaA_ig~CT4jQ_=uok^?eS_>%6l_Ua5KWscJJEIaR~PH>nn? z3WQ@vbXVzw-&D8j$j=sLZJXYsyh=0s+prWy&lP4YwZ3Vc$jwFHR~5Kg*PJz8RO5pw zst)hw(EM1{6P)jqM{X$e@(^nuPCb_Sj>8RXz+kv{@aE`^$jV9 zhOgCgANP}^&Ax|cfjt#(a5XaW4}7X!G#B<`Gs9)I(kniODhdOp_>bE(^;aCrv?9Gc zl%$a%JBizuC#h--T{z) zm{dLC)^WT-T(w}^Vo5A|yO}3dK%wJlxDjz$jo~~OtEtX3jH~2khL%FmRq>R z(udit#0#CNfO4u&K;zY6SOnNPo137f0eAP|B;Y|Mkr#nR>*9HrvY2v1GZD~5_(QLd z{GHqu+!u^l`1R%cqg6dV`!jYRDr+GlO`GqN0To3=Q`zmy+UN%wryHISfl1~6f17dv ary_)@GrCe?S;+a*0x-I5s$Zk){OlhZDs-6u literal 0 HcmV?d00001 -- Gitee From 705c65d9bb0a70ed3a9b07652cde47bafe70652a Mon Sep 17 00:00:00 2001 From: wusongqing Date: Wed, 16 Mar 2022 19:29:22 +0800 Subject: [PATCH 3/4] updated docs Signed-off-by: wusongqing --- zh-cn/application-dev/media/audio-playback.md | 164 +- zh-cn/application-dev/media/audio-recorder.md | 389 +++-- zh-cn/application-dev/media/video-playback.md | 178 ++- zh-cn/application-dev/media/video-recorder.md | 295 ++-- .../reference/apis/js-apis-media.md | 1404 ++++++++--------- 5 files changed, 1213 insertions(+), 1217 deletions(-) diff --git a/zh-cn/application-dev/media/audio-playback.md b/zh-cn/application-dev/media/audio-playback.md index a142a8b0106..922e2158872 100644 --- a/zh-cn/application-dev/media/audio-playback.md +++ b/zh-cn/application-dev/media/audio-playback.md @@ -1,70 +1,70 @@ -# 音频播放开发指导 +# Audio Playback Development -## 场景介绍 +## When to Use -音频播放的主要工作是将音频数据转码为可听见的音频模拟信号并通过输出设备进行播放,同时对播放任务进行管理。 +You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks. -**图1** 音频播放状态机 +**Figure 1** Playback status -![zh-ch_image_audio_state_machine](figures/zh-ch_image_audio_state_machine.png) +![en-us_image_audio_state_machine](figures/en-us_image_audio_state_machine.png) -**图2** 音频播放零层图 +**Figure 2** Layer 0 diagram of audio playback -![zh-ch_image_audio_player](figures/zh-ch_image_audio_player.png) +![en-us_image_audio_player](figures/en-us_image_audio_player.png) -## 开发步骤 +## How to Develop -详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md) +For details about the APIs used for audio playback, see [js-apis-media.md](../reference/apis/js-apis-media.md). -### 全流程场景 +### Full-Process Scenario -包含流程:创建实例,设置uri,播放音频,跳转播放位置,设置音量,暂停播放,获取轨道信息,停止播放,重置,释放资源等流程。 +The full audio playback process includes creating an instance, setting the URI, playing audio, seeking to the playback position, setting the volume, pausing playback, obtaining track information, stopping playback, resetting resources, and releasing resources. -AudioPlayer支持的src媒体源输入类型可参考:[src属性说明](../reference/apis/js-apis-media.md#audioplayer_属性) +For details about the **src** media source input types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_attributes). ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' function SetCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - //播放界面可切换至已准备好,可点击播放按钮进行播放状态 + // The playback page is ready. You can click the Play button to start the playback. }); - audioPlayer.on('play', () => { //设置'play'事件回调 + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); - //将播放按钮切换至可暂停状态 + // The Play button is changed to the pausable state. }); - audioPlayer.on('pause', () => { //设置'pause'事件回调 + audioPlayer.on('pause', () => { // Set the 'pause' event callback. console.info('audio pause success'); - //将播放按钮切换至可播放状态 + // The Play button is changed to the playable state. }); - audioPlayer.on('stop', () => { //设置'stop'事件回调 + audioPlayer.on('stop', () => { // Set the 'stop' event callback. console.info('audio stop success'); - //播放停止,播放进度条归零,播放按钮切换至可播放状态 + // The playback stops, the playback progress bar returns to 0, and the Play button is changed to the playable state. }); - audioPlayer.on('reset', () => { //设置'reset'事件回调 + audioPlayer.on('reset', () => { // Set the 'reset' event callback. console.info('audio reset success'); - //需重新设置src属性后,可继续播放其他音频 + // You can reconfigure the src attribute to play another audio file. }); - audioPlayer.on('timeUpdate', (seekDoneTime) => {//设置'timeUpdate'事件回调 + audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback. if (typeof(seekDoneTime) == 'undefined') { console.info('audio seek fail'); return; } console.info('audio seek success, and seek time is ' + seekDoneTime); - //播放进度条更新到seek对应的位置 + // The playback progress bar is updated to the seek position. }); - audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调 + audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. console.info('audio volumeChange success'); - //更新音量显示 + // Display the updated volume. }); - audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发 + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. console.info('audio play finish'); }); - audioPlayer.on('error', (error) => { //设置'error'事件回调 + audioPlayer.on('error', (error) => { // Set the 'error' event callback. console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errMessage is ${error.message}`); @@ -79,10 +79,10 @@ function printfDescription(obj) { } } -//1、创建实例 +// 1. Create an audioPlayer instance. let audioPlayer = media.createAudioPlayer(); -SetCallBack(audioPlayer); //设置事件回调 -//2、用户选择音频,设置uri +SetCallBack(audioPlayer); // Set the event callbacks. +// 2. Set the URI of the audio file. let fdPath = 'fd://' let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; await fileIO.open(path).then(fdNumber) => { @@ -94,17 +94,17 @@ await fileIO.open(path).then(fdNumber) => { console.info('open fd failed err is' + err); }); -audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 -//3、播放音频 -audioPlayer.play(); //需等待'dataLoad'事件回调完成后,才可调用play进行播放,触发'play'事件回调 -//4、跳转播放位置 -audioPlayer.seek(30000); //触发'timeUpdate'事件回调,seek到30000ms处播放 -//5、设置音量 -audioPlayer.setVolume(0.5); //触发'volumeChange'事件回调 -//6、暂停播放 -audioPlayer.pause(); //触发'pause'事件回调,暂停播放 -//7、获取轨道信息 -audioPlayer.getTrackDescription((error, arrlist) => { //通过回调方式获取音频轨道信息 +audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. +// 3. Play the audio. +audioPlayer.play(); // The play() method can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is triggered. +// 4. Seek to the playback position. +audioPlayer.seek(30000); // Trigger the 'timeUpdate' event callback, and seek to 30000 ms for playback. +// 5. Set the volume. +audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. +// 6. Pause the playback. +audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. +// 7. Obtain the track information. +audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. if (typeof (arrlist) != 'undefined') { for (let i = 0; i < arrlist.length; i++) { printfDescription(arrlist[i]); @@ -113,39 +113,39 @@ audioPlayer.getTrackDescription((error, arrlist) => { //通过回调方式获 console.log(`audio getTrackDescription fail, error:${error.message}`); } }); -//8、停止播放 -audioPlayer.stop(); //触发'stop'事件回调 -//9、重置播放资源 -audioPlayer.reset(); //触发'reset'事件回调后,重新设置src属性,可完成切歌 -//10、释放资源 -audioPlayer.release(); //audioPlayer资源被销毁 +// 8. Stop playback. +audioPlayer.stop(); // Trigger the 'stop' event callback. +// 9. Reset the playback resources. +audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. +// 10. Release the resource. +audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; ``` -### 正常播放场景 +### Normal Playback Scenario ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' function SetCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调 + audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { //设置'play'事件回调 + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); }); - audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发 + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. console.info('audio play finish'); - audioPlayer.release(); //audioPlayer资源被销毁 + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); } -let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例 -SetCallBack(audioPlayer); //设置事件回调 -/* 用户选择视频设置fd(本地播放) */ +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +SetCallBack(audioPlayer); // Set the event callbacks. +/* Set the FD (local playback) of the audio file selected by the user. */ let fdPath = 'fd://' let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; await fileIO.open(path).then(fdNumber) => { @@ -157,33 +157,33 @@ await fileIO.open(path).then(fdNumber) => { console.info('open fd failed err is' + err); }); -audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 +audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. ``` -### 切歌场景 +### Switching to the Next Song ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' function SetCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调 + audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { //设置'play'事件回调 + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); }); - audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发 + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. console.info('audio play finish'); - audioPlayer.release(); //audioPlayer资源被销毁 + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); } -let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例 -SetCallBack(audioPlayer); //设置事件回调 -/* 用户选择视频设置fd(本地播放) */ +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +SetCallBack(audioPlayer); // Set the event callbacks. +/* Set the FD (local playback) of the audio file selected by the user. */ let fdPath = 'fd://' let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; await fileIO.open(path).then(fdNumber) => { @@ -195,11 +195,11 @@ await fileIO.open(path).then(fdNumber) => { console.info('open fd failed err is' + err); }); -audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 -/* 播放一段时间后,下发切歌指令 */ +audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. +/* Send the instruction to switch to the next song after a period of time. */ audioPlayer.reset(); -/* 用户选择视频设置fd(本地播放) */ +/* Set the FD (local playback) of the audio file selected by the user. */ let fdNextPath = 'fd://' let nextPath = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; await fileIO.open(nextPath).then(fdNumber) => { @@ -213,31 +213,31 @@ await fileIO.open(nextPath).then(fdNumber) => { audioPlayer.src = fdNextPath; ``` -### 单曲循环场景 +### Looping a Song ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' function SetCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); //调用play方法开始播放,触发'play'事件回调 + audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { //设置'play'事件回调 + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); }); - audioPlayer.on('finish', () => { //设置'finish'事件回调,播放完成触发 + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. console.info('audio play finish'); - audioPlayer.release(); //audioPlayer资源被销毁 + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); } -let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例 -SetCallBack(audioPlayer); //设置事件回调 +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +SetCallBack(audioPlayer); // Set the event callbacks. -/* 用户选择视频设置fd(本地播放) */ +/* Set the FD (local playback) of the audio file selected by the user. */ let fdPath = 'fd://' let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; await fileIO.open(path).then(fdNumber) => { @@ -249,6 +249,6 @@ await fileIO.open(path).then(fdNumber) => { console.info('open fd failed err is' + err); }); -audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 -audioPlayer.loop = true; //设置循环播放属性 -``` \ No newline at end of file +audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. +audioPlayer.loop = true; // Set the loop playback attribute. +``` diff --git a/zh-cn/application-dev/media/audio-recorder.md b/zh-cn/application-dev/media/audio-recorder.md index 7e52686c95e..0eed7ce6e20 100644 --- a/zh-cn/application-dev/media/audio-recorder.md +++ b/zh-cn/application-dev/media/audio-recorder.md @@ -1,195 +1,194 @@ -# 音频录制开发指导 - -## 场景介绍 - -音频录制的主要工作是捕获音频信号,完成音频编码并保存到文件中,帮助开发者轻松实现音频录制功能。它允许调用者指定音频录制的采样率、声道数、编码格式、封装格式、文件路径等参数。 - -**图1** 音频录制状态机 - -![zh-ch_image_audio_recorder_state_machine](figures/zh-ch_image_audio_recorder_state_machine.png) - - - -**图2** 音频录制零层图 - -![zh-ch_image_audio_recorder_zero](figures/zh-ch_image_audio_recorder_zero.png) - -## 开发步骤 - -详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md) - -### 全流程场景 - -包含流程:创建实例,设置录制参数,录制音频,暂停录制,恢复录制,停止录制,释放资源等流程。 - -```js -import media from '@ohos.multimedia.media' -import mediaLibrary from '@ohos.multimedia.mediaLibrary' - -let testFdNumber; - -function SetCallBack(audioRecorder) { - audioRecorder.on('prepare', () => { // 设置'prepare'事件回调 - console.log('prepare success'); - // 录制界面可切换至已准备好,可点击录制按钮进行录制 - }); - audioRecorder.on('start', () => { // 设置'start'事件回调 - console.log('audio recorder start success'); - // 将录制按钮切换至可暂停状态 - }); - audioRecorder.on('pause', () => { // 设置'pause'事件回调 - console.log('audio recorder pause success'); - // 将录制按钮切换至可录制状态 - }); - audioRecorder.on('resume', () => { // 设置'resume'事件回调 - console.log('audio recorder resume success'); - // 将录制按钮切换至可暂停状态 - }); - audioRecorder.on('stop', () => { // 设置'stop'事件回调 - console.log('audio recorder stop success'); - }); - audioRecorder.on('release', () => { // 设置'release'事件回调 - console.log('audio recorder release success'); - }); - audioRecorder.on('reset', () => { // 设置'reset'事件回调 - console.log('audio recorder reset success'); - // 需要重新设置录制参数才能再次录制 - }); - audioRecorder.on('error', (error) => { // 设置'error'事件回调 - console.info(`audio error called, errName is ${error.name}`); - console.info(`audio error called, errCode is ${error.code}`); - console.info(`audio error called, errMessage is ${error.message}`); - }); -} - -// pathName是传入的录制文件名,例如:01.mp3,生成后的文件地址:/storage/media/100/local/files/Movies/01.mp3 -// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA -async function getFd(pathName) { - let displayName = pathName; - const mediaTest = mediaLibrary.getMediaLibrary(); - let fileKeyObj = mediaLibrary.FileKey; - let mediaType = mediaLibrary.MediaType.VIDEO; - let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); - let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); - if (dataUri != undefined) { - let args = dataUri.id.toString(); - let fetchOp = { - selections : fileKeyObj.ID + "=?", - selectionArgs : [args], - } - let fetchFileResult = await mediaTest.getFileAssets(fetchOp); - let fileAsset = await fetchFileResult.getAllObject(); - let fdNumber = await fileAsset[0].open('Rw'); - fdNumber = "fd://" + fdNumber.toString(); - testFdNumber = fdNumber; - } -} - -await getFd('01.mp3'); - -// 1.创建实例 -let audioRecorder = media.createAudioRecorder(); -// 2.设置回调 -SetCallBack(audioRecorder); -// 3.设置录制参数 -let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC , - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : media.AudioOutputFormat.AAC_ADTS, - uri : testFdNumber, // testFdNumber由getFd生成 - location : { latitude : 30, longitude : 130}, -} -audioRecorder.prepare(audioRecorderConfig); -// 4.开始录制 -audioRecorder.start(); // 需等待'prepare'事件回调完成后,才可调用start进行录制,触发'start'事件回调 -// 5.暂停录制 -audioRecorder.pause(); // 需等待'start'事件回调完成后,才可调用pause进行暂停,触发'pause'事件回调 -// 6.恢复录制 -audioRecorder.resume(); // 需等待'pause'事件回调完成后,才可调用resume进行录制,触发'resume'事件回调 -// 7.停止录制 -audioRecorder.stop(); // 需等待'start'或'resume'事件回调完成后,才可调用stop进行暂停,触发'stop'事件回调 -// 8.重置录制 -audioRecorder.reset(); // 触发'reset'事件回调后,重新进行prepare,才可重新录制 -// 9.释放资源 -audioRecorder.release(); // audioRecorder资源被销毁 -audioRecorder = undefined; -``` - -### 正常录制场景 - -与全流程场景不同,不包括暂停录制,恢复录制的过程。 - -```js -import media from '@ohos.multimedia.media' -import mediaLibrary from '@ohos.multimedia.mediaLibrary' - -let testFdNumber; - -function SetCallBack(audioPlayer) { - audioRecorder.on('prepare', () => { // 设置'prepare'事件回调 - console.log('prepare success'); - // 录制界面可切换至已准备好,可点击录制按钮进行录制 - }); - audioRecorder.on('start', () => { // 设置'start'事件回调 - console.log('audio recorder start success'); - // 将录制按钮切换至可暂停状态 - }); - audioRecorder.on('stop', () => { // 设置'stop'事件回调 - console.log('audio recorder stop success'); - }); - audioRecorder.on('release', () => { // 设置'release'事件回调 - console.log('audio recorder release success'); - }); -} - -// pathName是传入的录制文件名,例如:01.mp3,生成后的文件地址:/storage/media/100/local/files/Movies/01.mp3 -// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA -async function getFd(pathName) { - let displayName = pathName; - const mediaTest = mediaLibrary.getMediaLibrary(); - let fileKeyObj = mediaLibrary.FileKey; - let mediaType = mediaLibrary.MediaType.VIDEO; - let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); - let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); - if (dataUri != undefined) { - let args = dataUri.id.toString(); - let fetchOp = { - selections : fileKeyObj.ID + "=?", - selectionArgs : [args], - } - let fetchFileResult = await mediaTest.getFileAssets(fetchOp); - let fileAsset = await fetchFileResult.getAllObject(); - let fdNumber = await fileAsset[0].open('Rw'); - fdNumber = "fd://" + fdNumber.toString(); - testFdNumber = fdNumber; - } -} - -await getFd('01.mp3'); - -// 1.创建实例 -let audioRecorder = media.createAudioRecorder(); -// 2.设置回调 -SetCallBack(audioRecorder); -// 3.设置录制参数 -let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC , - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : media.AudioOutputFormat.AAC_ADTS, - uri : testFdNumber, // testFdNumber由getFd生成 - location : { latitude : 30, longitude : 130}, -} -audioRecorder.prepare(audioRecorderConfig) -// 4.开始录制 -audioRecorder.start(); // 需等待'prepare'事件回调完成后,才可调用start进行录制,触发'start'事件回调 -// 5.停止录制 -audioRecorder.stop(); // 需等待'start'或'resume'事件回调完成后,才可调用stop进行暂停,触发'stop'事件回调 -// 6.释放资源 -audioRecorder.release(); // audioRecorder资源被销毁 -audioRecorder = undefined; -``` - +# Audio Recording Development + +## When to Use + +During audio recording, audio signals are captured, encoded, and saved to files. You can specify parameters such as the sampling rate, number of audio channels, encoding format, encapsulation format, and file path for audio recording. + +**Figure 1** Audio recording state transition + +![en-us_image_audio_recorder_state_machine](figures/en-us_image_audio_recorder_state_machine.png) + + + +**Figure 2** Layer 0 diagram of audio recording + +![en-us_image_audio_recorder_zero](figures/en-us_image_audio_recorder_zero.png) + +## How to Develop + +For details about the APIs used for audio recording, see [js-apis-media.md](../reference/apis/js-apis-media.md). + +### Full-Process Scenario + +The full audio recording process includes creating an instance, setting recording parameters, starting, pausing, resuming, and stopping recording, and releasing resources. + +```js +import media from '@ohos.multimedia.media' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +let testFdNumber; + +function SetCallBack(audioRecorder) { + audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. + console.log('prepare success'); + // The recording page is ready. You can click the Record button to start recording. + }); + audioRecorder.on('start', () => { // Set the 'start' event callback. + console.log('audio recorder start success'); + // The Record button is changed to the pausable state. + }); + audioRecorder.on('pause', () => { // Set the 'pause' event callback. + console.log('audio recorder pause success'); + // The Record button is changed to the recordable state. + }); + audioRecorder.on('resume', () => { // Set the 'resume' event callback. + console.log('audio recorder resume success'); + // The Record button is changed to the pausable state. + }); + audioRecorder.on('stop', () => { // Set the 'stop' event callback. + console.log('audio recorder stop success'); + }); + audioRecorder.on('release', () => { // Set the 'release' event callback. + console.log('audio recorder release success'); + }); + audioRecorder.on('reset', () => { // Set the 'reset' event callback. + console.log('audio recorder reset success'); + // You need to reset the recording parameters for another recording. + }); + audioRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); + console.info(`audio error called, errCode is ${error.code}`); + console.info(`audio error called, errMessage is ${error.message}`); + }); +} + +// pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Movies/01.mp3. +// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. +async function getFd(pathName) { + let displayName = pathName; + const mediaTest = mediaLibrary.getMediaLibrary(); + let fileKeyObj = mediaLibrary.FileKey; + let mediaType = mediaLibrary.MediaType.VIDEO; + let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); + let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); + if (dataUri != undefined) { + let args = dataUri.id.toString(); + let fetchOp = { + selections : fileKeyObj.ID + "=?", + selectionArgs : [args], + } + let fetchFileResult = await mediaTest.getFileAssets(fetchOp); + let fileAsset = await fetchFileResult.getAllObject(); + let fdNumber = await fileAsset[0].open('Rw'); + fdNumber = "fd://" + fdNumber.toString(); + testFdNumber = fdNumber; + } +} + +await getFd('01.mp3'); + +// 1. Create an AudioRecorder instance. +let audioRecorder = media.createAudioRecorder(); +// 2. Set the callbacks. +SetCallBack(audioRecorder); +// 3. Set the recording parameters. +let audioRecorderConfig = { + audioEncoder : media.AudioEncoder.AAC_LC , + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : testFdNumber, // testFdNumber is generated by getFd. + location : { latitude : 30, longitude : 130}, +} +audioRecorder.prepare(audioRecorderConfig); +// 4. Start recording. +audioRecorder.start(); // The start method can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete. +// 5. Pause recording. +audioRecorder.pause(); // The pause method can be called to trigger the 'pause' event callback only after the 'start' event callback is complete. +// 6. Resume recording. +audioRecorder.resume(); // The resume method can be called to trigger the 'resume' event callback only after the 'pause' event callback is complete. +// 7. Stop recording. +audioRecorder.stop(); // The stop method can be called to trigger the 'stop' event callback only after the 'start' or 'resume' event callback is complete. +// 8. Reset recording. +audioRecorder.reset(); // The prepare method can be called for another recording only after the 'reset' event callback is complete. +// 9. Release resources. +audioRecorder.release(); // The AudioRecorder resource is destroyed. +audioRecorder = undefined; +``` + +### Normal Recording Scenario + +Unlike the full-process scenario, the normal recording scenario does not include the process of pausing and resuming recording. + +```js +import media from '@ohos.multimedia.media' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +let testFdNumber; + +function SetCallBack(audioPlayer) { + audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. + console.log('prepare success'); + // The recording page is ready. You can click the Record button to start recording. + }); + audioRecorder.on('start', () => { // Set the 'start' event callback. + console.log('audio recorder start success'); + // The Record button is changed to the pausable state. + }); + audioRecorder.on('stop', () => { // Set the 'stop' event callback. + console.log('audio recorder stop success'); + }); + audioRecorder.on('release', () => { // Set the 'release' event callback. + console.log('audio recorder release success'); + }); +} + +// pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Movies/01.mp3. +// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. +async function getFd(pathName) { + let displayName = pathName; + const mediaTest = mediaLibrary.getMediaLibrary(); + let fileKeyObj = mediaLibrary.FileKey; + let mediaType = mediaLibrary.MediaType.VIDEO; + let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); + let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); + if (dataUri != undefined) { + let args = dataUri.id.toString(); + let fetchOp = { + selections : fileKeyObj.ID + "=?", + selectionArgs : [args], + } + let fetchFileResult = await mediaTest.getFileAssets(fetchOp); + let fileAsset = await fetchFileResult.getAllObject(); + let fdNumber = await fileAsset[0].open('Rw'); + fdNumber = "fd://" + fdNumber.toString(); + testFdNumber = fdNumber; + } +} + +await getFd('01.mp3'); + +// 1. Create an AudioRecorder instance. +let audioRecorder = media.createAudioRecorder(); +// 2. Set the callbacks. +SetCallBack(audioRecorder); +// 3. Set the recording parameters. +let audioRecorderConfig = { + audioEncoder : media.AudioEncoder.AAC_LC , + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : testFdNumber, // testFdNumber is generated by getFd. + location : { latitude : 30, longitude : 130}, +} +audioRecorder.prepare(audioRecorderConfig) +// 4. Start recording. +audioRecorder.start(); // The start method can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete. +// 5. Stop recording. +audioRecorder.stop(); // The stop method can be called to trigger the 'stop' event callback only after the 'start' or 'resume' event callback is complete. +// 6. Release resources. +audioRecorder.release(); // The AudioRecorder resource is destroyed. +audioRecorder = undefined; +``` diff --git a/zh-cn/application-dev/media/video-playback.md b/zh-cn/application-dev/media/video-playback.md index 9f2e155c728..29a31dcc5f1 100644 --- a/zh-cn/application-dev/media/video-playback.md +++ b/zh-cn/application-dev/media/video-playback.md @@ -1,65 +1,65 @@ -# 视频播放开发指导 +# Video Playback Development -## 场景介绍 +## When to Use -视频播放的主要工作是将视频数据转码并输出到设备进行播放,同时管理播放任务。本文将对视频播放全流程、视频切换、视频循环播放等场景开发进行介绍说明。 +You can use video playback APIs to convert video data into visible signals, play the signals using output devices, and manage playback tasks. This document describes the following video playback development scenarios: full-process, normal playback, video switching, and loop playback. -**图1** 视频播放状态机 +**Figure 1** Video playback state transition -![zh-ch_image_video_state_machine](figures/zh-ch_image_video_state_machine.png) +![en-us_image_video_state_machine](figures/en-us_image_video_state_machine.png) -**图2** 视频播放零层图 +**Figure 2** Layer 0 diagram of video playback -![zh-ch_image_video_player](figures/zh-ch_image_video_player.png) +![en-us_image_video_player](figures/en-us_image_video_player.png) -*注意:视频播放需要显示、音频、编解码等硬件能力。 +Note: Video playback requires hardware capabilities such as display, audio, and codec. -1. 三方应用从Xcomponent组件获取surfaceID。 -2. 三方应用把surfaceID传递给VideoPlayer JS。 -3. 媒体服务把帧数据flush给surface buffer。 +1. A third-party application obtains a surface ID from the Xcomponent. +2. The third-party application transfers the surface ID to the VideoPlayer JS. +3. The media service flushes the frame data to the surface buffer. -## 开发步骤 +## How to Develop -详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md) +For details about the APIs used for video playback, see [js-apis-media.md](../reference/apis/js-apis-media.md). -### 全流程场景 +### Full-Process Scenario -包含流程:创建实例,设置url,设置SurfaceId,准备播放视频,播放视频,暂停播放,获取轨道信息,跳转播放位置,设置音量,设置倍速,结束播放,重置,释放资源等流程。 +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. -VideoPlayer支持的url媒体源输入类型可参考:[url属性说明](../reference/apis/js-apis-media.md#videoplayer_属性) +For details about the **url** media source input types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_attributes). -Xcomponent创建方法可参考:[Xcomponent创建方法](#Xcomponent创建方法) +For details about how to create an Xcomponent, see [Xcomponent Creation](#Xcomponent). ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' -let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象 -let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID +let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method. +let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface. -// 调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中,该接口由XComponent组件默认加载,非主动调用 +// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded. LoadXcomponent() { surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); console.info('LoadXcomponent surfaceID is' + surfaceID); } -// 函数调用发生错误时用于上报错误信息 +// Report an error in the case of a function invocation failure. function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Message is ${error.message}`); } -// 当函数调用发生异常时用于上报错误信息 +// Report an error in the case of a function invocation 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}`); } -// 用于打印视频轨道信息 +// Used to print the video track information. function printfDescription(obj) { for (let item in obj) { let property = obj[item]; @@ -68,7 +68,7 @@ function printfDescription(obj) { } } -// 调用createVideoPlayer接口返回videoPlayer实例对象 +// Call createVideoPlayer to create a VideoPlayer instance. await media.createVideoPlayer().then((video) => { if (typeof (video) != 'undefined') { console.info('createVideoPlayer success!'); @@ -78,7 +78,7 @@ await media.createVideoPlayer().then((video) => { } }, failureCallback).catch(catchCallback); -// 用户选择视频设置fd(本地播放) +// Set the FD (local playback) of the video file selected by the user. let fdPath = 'fd://' let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; await fileIO.open(path).then(fdNumber) => { @@ -92,27 +92,27 @@ await fileIO.open(path).then(fdNumber) => { videoPlayer.url = fdPath; -// 设置surfaceID用于显示视频画面 +// Set the surface ID to display the video image. await videoPlayer.setDisplaySurface(surfaceID).then(() => { console.info('setDisplaySurface success'); }, failureCallback).catch(catchCallback); -// 调用prepare完成播放前准备工作 +// Call the prepare interface to prepare for playback. await videoPlayer.prepare().then(() => { console.info('prepare success'); }, failureCallback).catch(catchCallback); -// 调用play接口正式开始播放 +// Call the play interface to start playback. await videoPlayer.play().then(() => { console.info('play success'); }, failureCallback).catch(catchCallback); -// 暂停播放 +// Pause playback. await videoPlayer.pause().then(() => { console.info('pause success'); }, failureCallback).catch(catchCallback); -// 通过promise回调方式获取视频轨道信息 +// Use a promise to obtain the video track information. let arrayDescription; await videoPlayer.getTrackDescription().then((arrlist) => { if (typeof (arrlist) != 'undefined') { @@ -126,74 +126,74 @@ for (let i = 0; i < arrayDescription.length; i++) { printfDescription(arrayDescription[i]); } -// 跳转播放时间到50s位置,具体入参意义请参考接口文档 +// 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); -// 相关对象置undefined +// Set the related instances to undefined. videoPlayer = undefined; surfaceID = undefined; ``` -### 正常播放场景 +### Normal Playback Scenario ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' -let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象 -let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID +let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method. +let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface. -// 调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中,该接口由XComponent组件默认加载,非主动调用 +// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded. LoadXcomponent() { surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); console.info('LoadXcomponent surfaceID is' + surfaceID); } -// 函数调用发生错误时用于上报错误信息 +// Report an error in the case of a function invocation failure. function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Message is ${error.message}`); } -// 当函数调用发生异常时用于上报错误信息 +// Report an error in the case of a function invocation 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}`); } -// 设置'playbackCompleted'事件回调,播放完成触发 +// Set the 'playbackCompleted' event callback, which is triggered when the playback is complete. function SetCallBack(videoPlayer) { videoPlayer.on('playbackCompleted', () => { console.info('video play finish'); @@ -207,7 +207,7 @@ function SetCallBack(videoPlayer) { }); } -// 调用createVideoPlayer接口返回videoPlayer实例对象 +// Call createVideoPlayer to create a VideoPlayer instance. await media.createVideoPlayer().then((video) => { if (typeof (video) != 'undefined') { console.info('createVideoPlayer success!'); @@ -217,10 +217,10 @@ await media.createVideoPlayer().then((video) => { } }, failureCallback).catch(catchCallback); -// 设置事件回调 +// Set the event callbacks. SetCallBack(videoPlayer); -// 用户选择视频设置fd(本地播放) +// Set the FD (local playback) of the video file selected by the user. let fdPath = 'fd://' let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; await fileIO.open(path).then(fdNumber) => { @@ -234,52 +234,52 @@ await fileIO.open(path).then(fdNumber) => { videoPlayer.url = fdPath; -// 设置surfaceID用于显示视频画面 +// Set the surface ID to display the video image. await videoPlayer.setDisplaySurface(surfaceID).then(() => { console.info('setDisplaySurface success'); }, failureCallback).catch(catchCallback); -// 调用prepare完成播放前准备工作 +// Call the prepare interface to prepare for playback. await videoPlayer.prepare().then(() => { console.info('prepare success'); }, failureCallback).catch(catchCallback); -// 调用play接口正式开始播放 +// Call the play interface to start playback. await videoPlayer.play().then(() => { console.info('play success'); }, failureCallback).catch(catchCallback); ``` -### 切视频场景 +### Switching to the Next Video Clip ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' -let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象 -let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID +let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method. +let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface. -// 调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中,该接口由XComponent组件默认加载,非主动调用 +// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded. LoadXcomponent() { surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); console.info('LoadXcomponent surfaceID is' + surfaceID); } -// 函数调用发生错误时用于上报错误信息 +// Report an error in the case of a function invocation failure. function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Message is ${error.message}`); } -// 当函数调用发生异常时用于上报错误信息 +// Report an error in the case of a function invocation 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}`); } -// 设置'playbackCompleted'事件回调,播放完成触发 +// Set the 'playbackCompleted' event callback, which is triggered when the playback is complete. function SetCallBack(videoPlayer) { videoPlayer.on('playbackCompleted', () => { console.info('video play finish'); @@ -293,7 +293,7 @@ function SetCallBack(videoPlayer) { }); } -// 调用createVideoPlayer接口返回videoPlayer实例对象 +// Call createVideoPlayer to create a VideoPlayer instance. await media.createVideoPlayer().then((video) => { if (typeof (video) != 'undefined') { console.info('createVideoPlayer success!'); @@ -303,10 +303,10 @@ await media.createVideoPlayer().then((video) => { } }, failureCallback).catch(catchCallback); -// 设置事件回调 +// Set the event callbacks. SetCallBack(videoPlayer); -// 用户选择视频设置fd(本地播放) +// Set the FD (local playback) of the video file selected by the user. let fdPath = 'fd://' let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; await fileIO.open(path).then(fdNumber) => { @@ -320,28 +320,28 @@ await fileIO.open(path).then(fdNumber) => { videoPlayer.url = fdPath; -// 设置surfaceID用于显示视频画面 +// Set the surface ID to display the video image. await videoPlayer.setDisplaySurface(surfaceID).then(() => { console.info('setDisplaySurface success'); }, failureCallback).catch(catchCallback); -// 调用prepare完成播放前准备工作 +// Call the prepare interface to prepare for playback. await videoPlayer.prepare().then(() => { console.info('prepare success'); }, failureCallback).catch(catchCallback); -// 调用play接口正式开始播放 +// Call the play interface to start playback. await videoPlayer.play().then(() => { console.info('play success'); }, failureCallback).catch(catchCallback); -// 播放一段时间后,下发切视频指令 -// 重置播放配置 +// Send the instruction to switch to the next video clip after a period of time. +// Reset the playback configuration. await videoPlayer.reset().then(() => { console.info('reset success'); }, failureCallback).catch(catchCallback); -// 用户选择视频设置fd(本地播放) +// Set the FD (local playback) of the video file selected by the user. let fdNextPath = 'fd://' let nextPath = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/02.mp4'; await fileIO.open(nextPath).then(fdNumber) => { @@ -355,52 +355,52 @@ await fileIO.open(nextPath).then(fdNumber) => { videoPlayer.url = fdNextPath; -// 设置surfaceID用于显示视频画面 +// Set the surface ID to display the video image. await videoPlayer.setDisplaySurface(surfaceID).then(() => { console.info('setDisplaySurface success'); }, failureCallback).catch(catchCallback); -// 调用prepare完成播放前准备工作 +// Call the prepare interface to prepare for playback. await videoPlayer.prepare().then(() => { console.info('prepare success'); }, failureCallback).catch(catchCallback); -// 调用play接口正式开始播放 +// Call the play interface to start playback. await videoPlayer.play().then(() => { console.info('play success'); }, failureCallback).catch(catchCallback); ``` -### 单个视频循环场景 +### Looping a Video Clip ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' -let videoPlayer = undefined; // 用于保存createVideoPlayer创建的对象 -let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceID +let videoPlayer = undefined; // Used to store instances created by calling the createVideoPlayer method. +let surfaceID = undefined; // Used to save the surface ID returned by the Xcomponent interface. -// 调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中,该接口由XComponent组件默认加载,非主动调用 +// The LoadXcomponent() method is used to obtain the surface ID and save it to the **surfaceID** variable. This method is automatically called when the Xcomponent is loaded. LoadXcomponent() { surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); console.info('LoadXcomponent surfaceID is' + surfaceID); } -// 函数调用发生错误时用于上报错误信息 +// Report an error in the case of a function invocation failure. function failureCallback(error) { console.info(`error happened,error Name is ${error.name}`); console.info(`error happened,error Code is ${error.code}`); console.info(`error happened,error Message is ${error.message}`); } -// 当函数调用发生异常时用于上报错误信息 +// Report an error in the case of a function invocation 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}`); } -// 设置'playbackCompleted'事件回调,播放完成触发 +// Set the 'playbackCompleted' event callback, which is triggered when the playback is complete. function SetCallBack(videoPlayer) { videoPlayer.on('playbackCompleted', () => { console.info('video play finish'); @@ -414,7 +414,7 @@ function SetCallBack(videoPlayer) { }); } -// 调用createVideoPlayer接口返回videoPlayer实例对象 +// Call createVideoPlayer to create a VideoPlayer instance. await media.createVideoPlayer().then((video) => { if (typeof (video) != 'undefined') { console.info('createVideoPlayer success!'); @@ -424,10 +424,10 @@ await media.createVideoPlayer().then((video) => { } }, failureCallback).catch(catchCallback); -// 设置事件回调 +// Set the event callbacks. SetCallBack(videoPlayer); -// 用户选择视频设置fd(本地播放) +// Set the FD (local playback) of the video file selected by the user. let fdPath = 'fd://' let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp4'; await fileIO.open(path).then(fdNumber) => { @@ -441,35 +441,33 @@ await fileIO.open(path).then(fdNumber) => { videoPlayer.url = fdPath; -// 设置surfaceID用于显示视频画面 +// Set the surface ID to display the video image. await videoPlayer.setDisplaySurface(surfaceID).then(() => { console.info('setDisplaySurface success'); }, failureCallback).catch(catchCallback); -// 调用prepare完成播放前准备工作 +// Call the prepare interface to prepare for playback. await videoPlayer.prepare().then(() => { console.info('prepare success'); }, failureCallback).catch(catchCallback); -// 设置循环播放属性 +// Set the loop playback attribute. videoPlayer.loop = true; -// 调用play接口正式开始播放 +// Call the play interface to start playback. await videoPlayer.play().then(() => { console.info('play success'); }, failureCallback).catch(catchCallback); ``` -### Xcomponent创建方法 - -播放视频中获取surfaceID依赖了Xcomponent,需要创建一个和xxx.js同名的xxx.hml文件,xxx.hml里面需要添加如下代码: +### Xcomponent Creation ```js - +The Xcomponent is used to obtain the surface ID during video playback. You need to create an xxx.hml file and add the following code to the xxx.hml file, where xxx is the same as that in the xxx.js file: // 设置窗口宽高等属性 + 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. ``` diff --git a/zh-cn/application-dev/media/video-recorder.md b/zh-cn/application-dev/media/video-recorder.md index e684b2230ad..11af1d39846 100644 --- a/zh-cn/application-dev/media/video-recorder.md +++ b/zh-cn/application-dev/media/video-recorder.md @@ -1,148 +1,147 @@ -# 视频录制开发指导 - -## 场景介绍 - -视频录制的主要工作是捕获音视频信号,完成音视频编码并保存到文件中,帮助开发者轻松实现音视频录制功能。它允许调用者指定录制的编码格式、封装格式、文件路径等参数。 - -**图1** 视频录制状态机 - -![zh-ch_image_video_recorder_state_machine](figures/zh-ch_image_video_recorder_state_machine.png) - - - -**图2** 视频录制零层图 - -![zh-ch_image_video_recorder_zero](figures/zh-ch_image_video_recorder_zero.png) - -## 开发步骤 - -详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md) - -### 全流程场景 - -包含流程:创建实例,设置录制参数,录制视频,暂停录制,恢复录制,停止录制,释放资源等流程。 - -```js -import media from '@ohos.multimedia.media' -import mediaLibrary from '@ohos.multimedia.mediaLibrary' - -let testFdNumber; - -// pathName是传入的录制文件名,例如:01.mp4,生成后的文件地址:/storage/media/100/local/files/Movies/01.mp4 -// 使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA -async function getFd(pathName) { - let displayName = pathName; - const mediaTest = mediaLibrary.getMediaLibrary(); - let fileKeyObj = mediaLibrary.FileKey; - let mediaType = mediaLibrary.MediaType.VIDEO; - let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); - let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); - if (dataUri != undefined) { - let args = dataUri.id.toString(); - let fetchOp = { - selections : fileKeyObj.ID + "=?", - selectionArgs : [args], - } - let fetchFileResult = await mediaTest.getFileAssets(fetchOp); - let fileAsset = await fetchFileResult.getAllObject(); - let fdNumber = await fileAsset[0].open('Rw'); - fdNumber = "fd://" + fdNumber.toString(); - testFdNumber = fdNumber; - } -} - -await getFd('01.mp4'); - -let videoProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : 'audio/mp4a-latm', - audioSampleRate : 48000, - fileFormat : 'mp4', - videoBitrate : 48000, - videoCodec : 'video/mp4v-es', - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 -} - -let videoConfig = { - audioSourceType : 1, - videoSourceType : 0, - profile : videoProfile, - url : testFdNumber, // testFdNumber由getFd生成 - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, -} - -// 当发生错误上上报的错误回调接口 -function failureCallback(error) { - console.info('error happened, error name is ' + error.name); - console.info('error happened, error code is ' + error.code); - console.info('error happened, error message is ' + error.message); -} - -// 当发生异常时,系统调用的错误回调接口 -function catchCallback(error) { - console.info('catch error happened, error name is ' + error.name); - console.info('catch error happened, error code is ' + error.code); - console.info('catch error happened, error message is ' + error.message); -} - -let videoRecorder = null; // videoRecorder空对象在createVideoRecorder成功后赋值 -let surfaceID = null; // 用于保存getInputSurface返回的surfaceID - -// 创建videoRecorder对象 -await media.createVideoRecorder().then((recorder) => { - console.info('case createVideoRecorder called'); - if (typeof (recorder) != 'undefined') { - videoRecorder = recorder; - console.info('createVideoRecorder success'); - } else { - console.info('createVideoRecorder failed'); - } -}, failureCallback).catch(catchCallback); - -// 获取surfaceID并保存下来传递给camera相关接口 -await videoRecorder.getInputSurface().then((surface) => { - console.info('getInputSurface success'); - surfaceID = surface; -}, failureCallback).catch(catchCallback); - -// 视频录制依赖相机相关接口,以下需要先调用相机起流接口后才能继续执行 - -// 视频录制启动接口 -await videoRecorder.start().then(() => { - console.info('start success'); -}, failureCallback).catch(catchCallback); - -// 调用pause接口时需要暂停camera出流 -await videoRecorder.pause().then(() => { - console.info('pause success'); -}, failureCallback).catch(catchCallback); - -// 调用resume接口时需要恢复camera出流 -await videoRecorder.resume().then(() => { - console.info('resume success'); -}, failureCallback).catch(catchCallback); - -// 停止camera出流后,停止视频录制 -await videoRecorder.stop().then(() => { - console.info('stop success'); -}, failureCallback).catch(catchCallback); - -// 重置录制相关配置 -await videoRecorder.reset().then(() => { - console.info('reset success'); -}, failureCallback).catch(catchCallback); - -// 释放视频录制相关资源并释放camera对象相关资源 -await videoRecorder.release().then(() => { - console.info('release success'); -}, failureCallback).catch(catchCallback); - -// 相关对象置null -videoRecorder = null; -surfaceID = null; -``` - +# Video Recording Development + +## When to Use + +During video recording, audio and video signals are captured, encoded, and saved to files. You can specify parameters such as the encoding format, encapsulation format, and file path for video recording. + +**Figure 1** Video recording state transition + +![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png) + + + +**Figure 2** Layer 0 diagram of video recording + +![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png) + +## How to Develop + +For details about the APIs used for video recording, see [js-apis-media.md](../reference/apis/js-apis-media.md). + +### Full-Process Scenario + +The full video recording process includes creating an instance, setting recording parameters, recording video, pausing, resuming, and stopping recording, and releasing resources. + +```js +import media from '@ohos.multimedia.media' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +let testFdNumber; + +// pathName indicates the passed recording file name, for example, 01.mp4. The generated file address is /storage/media/100/local/files/Movies/01.mp4. +// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. +async function getFd(pathName) { + let displayName = pathName; + const mediaTest = mediaLibrary.getMediaLibrary(); + let fileKeyObj = mediaLibrary.FileKey; + let mediaType = mediaLibrary.MediaType.VIDEO; + let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); + let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); + if (dataUri != undefined) { + let args = dataUri.id.toString(); + let fetchOp = { + selections : fileKeyObj.ID + "=?", + selectionArgs : [args], + } + let fetchFileResult = await mediaTest.getFileAssets(fetchOp); + let fileAsset = await fetchFileResult.getAllObject(); + let fdNumber = await fileAsset[0].open('Rw'); + fdNumber = "fd://" + fdNumber.toString(); + testFdNumber = fdNumber; + } +} + +await getFd('01.mp4'); + +let videoProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : 'audio/mp4a-latm', + audioSampleRate : 48000, + fileFormat : 'mp4', + videoBitrate : 48000, + videoCodec : 'video/mp4v-es', + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 +} + +let videoConfig = { + audioSourceType : 1, + videoSourceType : 0, + profile : videoProfile, + url: testFdNumber, // testFdNumber is generated by getFd. + orientationHint : 0, + location : { latitude : 30, longitude : 130 }, +} + +// Error callback triggered in the case of an error +function failureCallback(error) { + console.info('error happened, error name is ' + error.name); + console.info('error happened, error code is ' + error.code); + console.info('error happened, error message is ' + error.message); +} + +// Error callback triggered in the case of an exception +function catchCallback(error) { + console.info('catch error happened, error name is ' + error.name); + console.info('catch error happened, error code is ' + error.code); + console.info('catch error happened, error message is ' + error.message); +} + +let videoRecorder = null; // videoRecorder is an empty object and assigned with a value after createVideoRecorder is successfully called. +let surfaceID = null; // Used to save the surface ID returned by getInputSurface. + +// Create a VideoRecorder object. +await media.createVideoRecorder().then((recorder) => { + console.info('case createVideoRecorder called'); + if (typeof (recorder) != 'undefined') { + videoRecorder = recorder; + console.info('createVideoRecorder success'); + } else { + console.info('createVideoRecorder failed'); + } +}, failureCallback).catch(catchCallback); + +// Obtain the surface ID, save it, and pass it to camera-related interfaces. +await videoRecorder.getInputSurface().then((surface) => { + console.info('getInputSurface success'); + surfaceID = surface; +}, failureCallback).catch(catchCallback); + +// Video recording depends on camera-related interfaces. The following operations can be performed only after the video output start interface is invoked. + +// Start video recording. +await videoRecorder.start().then(() => { + console.info('start success'); +}, failureCallback).catch(catchCallback); + +// Pause video playback before the video output stop interface is invoked. +await videoRecorder.pause().then(() => { + console.info('pause success'); +}, failureCallback).catch(catchCallback); + +// Resume video playback after the video output start interface is invoked. +await videoRecorder.resume().then(() => { + console.info('resume success'); +}, failureCallback).catch(catchCallback); + +// Stop video recording after the video output stop interface is invoked. +await videoRecorder.stop().then(() => { + console.info('stop success'); +}, failureCallback).catch(catchCallback); + +// Reset the recording configuration. +await videoRecorder.reset().then(() => { + console.info('reset success'); +}, failureCallback).catch(catchCallback); + +// Release the video recording resources and camera object resources. +await videoRecorder.release().then(() => { + console.info('release success'); +}, failureCallback).catch(catchCallback); + +// Set the related object to null. +videoRecorder = null; +surfaceID = null; +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-media.md b/zh-cn/application-dev/reference/apis/js-apis-media.md index 7aec07780e5..f0c9c0d0398 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-media.md +++ b/zh-cn/application-dev/reference/apis/js-apis-media.md @@ -1,20 +1,20 @@ -# 媒体服务 +# Media -> **说明:** -> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> **NOTE** +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. -媒体子系统为开发者提供一套简单且易于理解的接口,使得开发者能够方便接入系统并使用系统的媒体资源。 +The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. -媒体子系统包含了音视频相关媒体业务,提供以下常用功能: +This subsystem offers various media services covering audio and video, which provide the following capabilities: -- 音频播放([AudioPlayer](#audioplayer)) -- 视频播放([VideoPlayer](#videoplayer8)) -- 音频录制([AudioRecorder](#audiorecorder)) -- 视频录制([VideoRecorder](#VideoRecorder8+)) +- Audio playback ([AudioPlayer](#audioplayer)) +- Video playback ([VideoPlayer](#videoplayer8)) +- Audio recording ([AudioRecorder](#audiorecorder)) +- Video recording ([VideoRecorder](#VideoRecorder8+)) -后续将提供以下功能:DataSource音视频播放、音视频编解码、容器封装解封装、媒体能力查询等功能。 +The following capabilities will be provided in later versions: data source audio/video playback, audio/video encoding and decoding, container encapsulation and decapsulation, and media capability query. -## 导入模块 +## Modules to Import ```js import media from '@ohos.multimedia.media'; @@ -24,17 +24,17 @@ import media from '@ohos.multimedia.media'; createAudioPlayer(): [AudioPlayer](#audioplayer) -同步方式创建音频播放实例。 +Creates an **AudioPlayer** instance in synchronous mode. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | --------------------------- | ------------------------------------------------------------ | -| [AudioPlayer](#audioplayer) | 返回AudioPlayer类实例,失败时返回null。可用于音频播放、暂停、停止等操作。 | +| [AudioPlayer](#audioplayer) | Returns the **AudioPlayer** instance if the operation is successful; returns **null** otherwise. After the instance is created, you can start, pause, or stop audio playback.| -**示例:** +**Example** ```js let audioPlayer = media.createAudioPlayer(); @@ -44,17 +44,17 @@ let audioPlayer = media.createAudioPlayer(); createVideoPlayer(callback: AsyncCallback\<[VideoPlayer](#videoplayer8)>): void -异步方式创建视频播放实例,通过注册回调函数获取返回值。 +Creates a **VideoPlayer** instance in asynchronous mode. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | 是 | 异步创建视频播放实例回调方法。 | +| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the **VideoPlayer** instance created.| -**示例:** +**Example** ```js let videoPlayer @@ -73,17 +73,17 @@ media.createVideoPlayer((error, video) => { createVideoPlayer: Promise<[VideoPlayer](#videoplayer8)> -异步方式创建视频播放实例,通过Promise获取返回值。 +Creates a **VideoPlayer** instance in asynchronous mode. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | ------------------------------------- | ----------------------------------- | -| Promise<[VideoPlayer](#videoplayer8)> | 异步创建视频播放实例Promise返回值。 | +| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the **VideoPlayer** instance created.| -**示例:** +**Example** ```js let videoPlayer @@ -109,17 +109,17 @@ await media.createVideoPlayer.then((video) => { createAudioRecorder(): AudioRecorder -创建音频录制的实例来控制音频的录制。 +Creates an **AudioRecorder** instance to control audio recording. -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | ------------------------------- | ----------------------------------------- | -| [AudioRecorder](#audiorecorder) | 返回AudioRecorder类实例,失败时返回null。 | +| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise.| -**示例:** +**Example** ```js let audiorecorder = media.createAudioRecorder(); @@ -129,17 +129,17 @@ let audiorecorder = media.createAudioRecorder(); createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder8)>): void -异步方式创建视频录制实例。通过注册回调函数获取返回值。 +Creates a **VideoRecorder** instance in asynchronous mode. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoRecorder](#videorecorder8)> | 是 | 异步创建视频录制实例回调方法。 | +| callback | AsyncCallback<[VideoRecorder](#videorecorder8)> | Yes | Callback used to return the **VideoRecorder** instance created.| -**示例:** +**Example** ```js let videoRecorder @@ -158,17 +158,17 @@ media.createVideoRecorder((error, video) => { createVideoRecorder: Promise<[VideoRecorder](#videorecorder8)> -异步方式创建视频录制实例。通过Promise获取返回值。 +Creates a **VideoRecorder** instance in asynchronous mode. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | ----------------------------------------- | ----------------------------------- | -| Promise<[VideoRecorder](#videorecorder8)> | 异步创建视频录制实例Promise返回值。 | +| Promise<[VideoRecorder](#videorecorder8)> | Promise used to return the **VideoRecorder** instance created.| -**示例:** +**Example** ```js let videoRecorder @@ -194,97 +194,97 @@ await media.createVideoRecorder.then((video) => { ## MediaErrorCode8+ -媒体服务错误类型枚举。 +Enumerates the media error codes. -| 名称 | 值 | 说明 | +| Name | Value | Description | | -------------------------- | ---- | ------------------------------------------------------------ | -| MSERR_OK | 0 | 表示操作成功。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MSERR_NO_MEMORY | 1 | 表示申请内存失败,系统可能无可用内存。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MSERR_OPERATION_NOT_PERMIT | 2 | 表示无权限执行此操作。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MSERR_INVALID_VAL | 3 | 表示传入入参无效。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MSERR_IO | 4 | 表示发生IO错误。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MSERR_TIMEOUT | 5 | 表示操作超时。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MSERR_UNKNOWN | 6 | 表示未知错误。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MSERR_SERVICE_DIED | 7 | 表示服务端失效。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MSERR_INVALID_STATE | 8 | 表示在当前状态下,不允许执行此操作。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MSERR_UNSUPPORTED | 9 | 表示在当前版本下,不支持此操作。
**系统能力:** SystemCapability.Multimedia.Media.Core | +| MSERR_OK | 0 | The operation is successful.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_NO_MEMORY | 1 | Failed to allocate memory. The system may have no available memory.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_OPERATION_NOT_PERMIT | 2 | No permission to perform this operation.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_INVALID_VAL | 3 | Invalid input parameter.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_IO | 4 | An I/O error occurs.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_TIMEOUT | 5 | The operation times out.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_UNKNOWN | 6 | An unknown error occurs.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_SERVICE_DIED | 7 | Invalid server.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_INVALID_STATE | 8 | The operation is not allowed in the current state.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MSERR_UNSUPPORTED | 9 | The operation is not supported in the current version.
**System capability**: SystemCapability.Multimedia.Media.Core| ## MediaType8+ -媒体类型枚举。 +Enumerates the media types. -| 名称 | 值 | 说明 | +| Name | Value | Description | | -------------- | ---- | ------------------------------------------------------------ | -| MEDIA_TYPE_AUD | 0 | 表示音频。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MEDIA_TYPE_VID | 1 | 表示视频。
**系统能力:** SystemCapability.Multimedia.Media.Core | +| MEDIA_TYPE_AUD | 0 | Media.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MEDIA_TYPE_VID | 1 | Video.
**System capability**: SystemCapability.Multimedia.Media.Core| ## CodecMimeType8+ -Codec MIME类型枚举。 +Enumerates the codec MIME types. -| 名称 | 值 | 说明 | +| Name | Value | Description | | ------------ | ----------------- | ------------------------------------------------------------ | -| VIDEO_MPEG4 | ”video/mp4v-es“ | 表示视频/mpeg4类型。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| AUDIO_AAC | "audio/mp4a-latm" | 表示音频/mp4a-latm类型。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| AUDIO_VORBIS | "audio/vorbis" | 表示音频/vorbis类型。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| AUDIO_FLAC | "audio/flac" | 表示音频/flac类型。
**系统能力:** SystemCapability.Multimedia.Media.Core | +| VIDEO_MPEG4 | "video/mp4v-es" | Video in MPEG-4 format.
**System capability**: SystemCapability.Multimedia.Media.Core| +| AUDIO_AAC | "audio/mp4a-latm" | Audio in MP4A-LATM format.
**System capability**: SystemCapability.Multimedia.Media.Core| +| AUDIO_VORBIS | "audio/vorbis" | Audio in Vorbis format.
**System capability**: SystemCapability.Multimedia.Media.Core| +| AUDIO_FLAC | "audio/flac" | Audio in FLAC format.
**System capability**: SystemCapability.Multimedia.Media.Core| ## MediaDescriptionKey8+ -媒体信息描述枚举。 +Enumerates the media description keys. -| 名称 | 值 | 说明 | +| Name | Value | Description | | ------------------------ | --------------- | ------------------------------------------------------------ | -| MD_KEY_TRACK_INDEX | "track_index" | 表示轨道序号,其对应键值类型为number。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MD_KEY_TRACK_TYPE | "track_type" | 表示轨道类型,其对应键值类型为number,参考[MediaType](#mediatype8)。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MD_KEY_CODEC_MIME | "codec_mime" | 表示codec_mime类型,其对应键值类型为string。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MD_KEY_DURATION | "duration" | 表示媒体时长,其对应键值类型为number,单位为ms。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MD_KEY_BITRATE | "bitrate" | 表示比特率,其对应键值类型为number,单位为bps。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MD_KEY_WIDTH | "width" | 表示视频宽度,其对应键值类型为number,单位为像素。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MD_KEY_HEIGHT | "height" | 表示视频高度,其对应键值类型为number,单位为像素。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MD_KEY_FRAME_RATE | "frame_rate" | 表示视频帧率,其对应键值类型为number,单位为100fps。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | 表示声道数,其对应键值类型为number。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | 表示采样率,其对应键值类型为number,单位为HZ。
**系统能力:** SystemCapability.Multimedia.Media.Core | +| MD_KEY_TRACK_INDEX | "track_index" | Track index, which is a number.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_TRACK_TYPE | "track_type" | Track type, which is a number. For details, see [MediaType](#mediatype8).
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_CODEC_MIME | "codec_mime" | Codec MIME type, which is a string.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_DURATION | "duration" | Media duration, which is a number, in units of ms.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_BITRATE | "bitrate" | Bit rate, which is a number, in units of bit/s.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_WIDTH | "width" | Video width, which is a number, in units of pixel.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_HEIGHT | "height" | Video height, which is a number, in units of pixel.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_FRAME_RATE | "frame_rate" | Video frame rate, which is a number, in units of 100 fps.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | Number of audio channels, which is a number.
**System capability**: SystemCapability.Multimedia.Media.Core| +| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | Sampling rate, which is a number, in units of Hz.
**System capability**: SystemCapability.Multimedia.Media.Core| ## BufferingInfoType8+ -缓存事件类型枚举。 +Enumerates the buffering event types. -| 名称 | 值 | 说明 | +| Name | Value | Description | | ----------------- | ---- | ------------------------------------------------------------ | -| BUFFERING_START | 1 | 表示开始缓存。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| BUFFERING_END | 2 | 表示结束缓存。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| BUFFERING_PERCENT | 3 | 表示缓存百分比。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| CACHED_DURATION | 4 | 表示缓存时长,单位为毫秒。
**系统能力:** SystemCapability.Multimedia.Media.Core | +| BUFFERING_START | 1 | Buffering starts.
**System capability**: SystemCapability.Multimedia.Media.Core| +| BUFFERING_END | 2 | Buffering ends.
**System capability**: SystemCapability.Multimedia.Media.Core| +| BUFFERING_PERCENT | 3 | Buffering progress, in percent.
**System capability**: SystemCapability.Multimedia.Media.Core| +| CACHED_DURATION | 4 | Cache duration, in milliseconds.
**System capability**: SystemCapability.Multimedia.Media.Core| ## AudioPlayer -音频播放管理类,用于管理和播放音频媒体。在调用AudioPlayer的方法前,需要先通过[createAudioPlayer()](#mediacreateaudioplayer)构建一个[AudioPlayer](#audioplayer)实例。 +Provides methods to manage and play audio. Before calling a method of **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayer) to create an **AudioPlayer** instance. -音频播放demo可参考:[音频播放开发指导](../../media/audio-playback.md) +For details about the audio playback demo, see [Audio Playback Development](../../media/audio-playback.md). -### 属性 +### Attributes -| 名称 | 类型 | 可读 | 可写 | 说明 | +| Name | Type | Readable| Writable| Description | | ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| src | string | 是 | 是 | 音频媒体URI,支持当前主流的音频格式(mp4、aac、mp3、ogg)。
**支持路径示例**:
1、fd类型播放:fd://xxx
![zh-cn_image_0000001164217678](figures/zh-cn_image_url.png)
2、http网络播放路径:开发中
3、hls网络播放路径:开发中
**注意事项**:
使用媒体素材需要获取读权限,否则无法正常播放。
**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer | -| loop | boolean | 是 | 是 | 音频循环播放属性,设置为'true'表示循环播放。
**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer | -| currentTime | number | 是 | 否 | 音频的当前播放位置。
**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer | -| duration | number | 是 | 否 | 音频时长。
**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer | -| state | [AudioState](#audiostate) | 是 | 否 | 音频播放的状态。
**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer | +| src | string | Yes | Yes | Audio media URI. The mainstream audio formats (MP4, AAC, MP3, and OGG) are supported.
**Example of supported URIs**:
1. FD playback: fd://xxx
![en-us_image_0000001164217678](figures/en-us_image_url.png)
2. HTTP network playback path (under development)
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| currentTime | number | Yes | No | Current audio playback position.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| duration | number | Yes | No | Audio duration.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| state | [AudioState](#audiostate) | Yes | No | Audio playback state.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| ### play play(): void -开始播放音频资源,需在[dataLoad](#on('play' | 'pause' | 'stop' | 'reset' | 'dataload' | 'finish' | 'volumechange'))事件成功触发后,才能调用play方法。 +Starts to play audio resources. This method can be called only after the [dataLoad](#on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange')) event is triggered. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**示例:** +**Example** ```js -audioPlayer.on('play', () => { //设置'play'事件回调 +audioPlayer.on('play', () => { // Set the 'play' event callback. console.log('audio play success'); }); audioPlayer.play(); @@ -294,14 +294,14 @@ audioPlayer.play(); pause(): void -暂停播放音频资源。 +Pauses audio playback. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**示例:** +**Example** ```js -audioPlayer.on('pause', () => { //设置'pause'事件回调 +audioPlayer.on('pause', () => { // Set the 'pause' event callback. console.log('audio pause success'); }); audioPlayer.pause(); @@ -311,14 +311,14 @@ audioPlayer.pause(); stop(): void -停止播放音频资源。 +Stops audio playback. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**示例:** +**Example** ```js -audioPlayer.on('stop', () => { //设置'stop'事件回调 +audioPlayer.on('stop', () => { // Set the 'stop' event callback. console.log('audio stop success'); }); audioPlayer.stop(); @@ -328,14 +328,14 @@ audioPlayer.stop(); reset(): void -切换播放音频资源。 +Switches the audio resource to be played. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**示例:** +**Example** ```js -audioPlayer.on('reset', () => { //设置'reset'事件回调 +audioPlayer.on('reset', () => { // Set the 'reset' event callback. console.log('audio reset success'); }); audioPlayer.reset(); @@ -345,61 +345,61 @@ audioPlayer.reset(); seek(timeMs: number): void -跳转到指定播放位置。 +Seeks to the specified playback position. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------ | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 | +| timeMs | number | Yes | Position to seek to, in milliseconds.| -**示例:** +**Example** ```js -audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调 +audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. if (typeof (seekDoneTime) == 'undefined') { console.info('audio seek fail'); return; } console.log('audio seek success. seekDoneTime: ' + seekDoneTime); }); -audioPlayer.seek(30000); //seek到30000ms的位置 +audioPlayer.seek(30000); // Seek to 30000 ms. ``` ### setVolume setVolume(vol: number): void -设置音量。 +Sets the volume. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| -**示例:** +**Example** ```js -audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调 +audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. console.log('audio volumeChange success'); }); -audioPlayer.setVolume(1); //设置音量到100% +audioPlayer.setVolume(1); // Set the volume to 100%. ``` ### release release(): void -释放音频资源。 +Releases the audio playback resource. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**示例:** +**Example** ```js audioPlayer.release(); @@ -410,17 +410,17 @@ audioPlayer = undefined; getTrackDescription(callback: AsyncCallback>): void -通过回调方式获取音频轨道信息。 +Obtains the audio track information. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------------- | -| callback | AsyncCallback> | 是 | 获取音频轨道信息回调方法。 | +| callback | AsyncCallback> | Yes | Callback used to return the audio track information obtained.| -**示例:** +**Example** ```js function printfDescription(obj) { @@ -446,17 +446,17 @@ audioPlayer.getTrackDescription((error, arrlist) => { getTrackDescription(): Promise> -通过Promise方式获取音频轨道信息。 +Obtains the audio track information. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | ------------------------------------------------------ | ------------------------------- | -| Promise> | 获取音频轨道信息Promise返回值。 | +| Promise> | Promise used to return the audio track information obtained.| -**示例:** +**Example** ```js function printfDescription(obj) { @@ -489,18 +489,18 @@ for (let i = 0; i < arrayDescription.length; i++) { on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void -开始订阅音频缓存更新事件。 +Subscribes to the audio buffering update event. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 音频缓存事件回调类型,支持的事件:'bufferingUpdate'。 | -| callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | 是 | 音频缓存事件回调方法。
[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 | +| type | string | Yes | Type of the event to subscribe to, which is 'bufferingUpdate' in this example. | +| callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| -**示例:** +**Example** ```js audioPlayer.on('bufferingUpdate', (infoType, value) => { @@ -513,61 +513,61 @@ audioPlayer.on('bufferingUpdate', (infoType, value) => { on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void -开始订阅音频播放事件。 +Subscribes to the audio playback events. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 播放事件回调类型,支持的事件包括:'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'。
- 'play':完成[play()](#play)调用,音频开始播放,触发该事件。
- 'pause':完成[pause()](#pause)调用,音频暂停播放,触发该事件。
- 'stop':完成[stop()](#stop)调用,音频停止播放,触发该事件。
- 'reset':完成[reset()](#reset7)调用,播放器重置,触发该事件。
- 'dataLoad':完成音频数据加载后触发该事件,即src属性设置完成后触发该事件。
- 'finish':完成音频播放后触发该事件。
- 'volumeChange':完成[setVolume()](#setvolume)调用,播放音量改变后触发该事件。 | -| callback | () => void | 是 | 播放事件回调方法。 | +| type | string | Yes | Type of the event to subscribe to. The following events are supported: 'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'
- The 'play' event is triggered when the [play()](#play) method is called and audio playback starts.
- The 'pause' event is triggered when the [pause()](#pause) method is called and audio playback is paused.
- The 'stop' event is triggered when the [stop()](#stop) method is called and audio playback stops.
- The 'reset' event is triggered when the [reset()](#reset7) method is called and audio playback is reset.
- The 'dataLoad' event is triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- The 'finish' event is triggered when the audio playback is finished.
- The 'volumeChange' event is triggered when the [setVolume()](#setvolume) method is called and the playback volume is changed.| +| callback | () => void | Yes | Callback invoked when the event is triggered. | -**示例:** +**Example** ```js -let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例 -audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); //开始播放,并触发'play'事件回调 + audioPlayer.play(); // Start the playback and trigger the 'play' event callback. }); -audioPlayer.on('play', () => { //设置'play'事件回调 +audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); - audioPlayer.seek(30000); //调用seek方法,并触发'timeUpdate'事件回调 + audioPlayer.seek(30000); // Call the seek() method and trigger the 'timeUpdate' event callback. }); -audioPlayer.on('pause', () => { //设置'pause'事件回调 +audioPlayer.on('pause', () => { // Set the 'pause' event callback. console.info('audio pause success'); - audioPlayer.stop(); //停止播放,并触发'stop'事件回调 + audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. }); -audioPlayer.on('reset', () => { //设置'reset'事件回调 +audioPlayer.on('reset', () => { // Set the 'reset' event callback. console.info('audio reset success'); - audioPlayer.release(); //释放播放实例资源 + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); -audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调 +audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. if (typeof(seekDoneTime) == "undefined") { console.info('audio seek fail'); return; } console.info('audio seek success, and seek time is ' + seekDoneTime); - audioPlayer.setVolume(0.5); //设置音量为50%,并触发'volumeChange'事件回调 + audioPlayer.setVolume(0.5); // Set the volume to 50% and trigger the 'volumeChange' event callback. }); -audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调 +audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. console.info('audio volumeChange success'); - audioPlayer.pause(); //暂停播放,并触发'pause'事件回调 + audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. }); -audioPlayer.on('finish', () => { //设置'finish'事件回调 +audioPlayer.on('finish', () => { // Set the 'finish' event callback. console.info('audio play finish'); - audioPlayer.stop(); //停止播放,并触发'stop'事件回调 + audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. }); -audioPlayer.on('error', (error) => { //设置'error'事件回调 +audioPlayer.on('error', (error) => { // Set the 'error' event callback. console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errMessage is ${error.message}`); }); -// 用户选择视频设置fd(本地播放) +// Set the FD (local playback) of the video file selected by the user. let fdPath = 'fd://' let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; await fileIO.open(path).then(fdNumber) => { @@ -578,109 +578,109 @@ await fileIO.open(path).then(fdNumber) => { }),catch((err) => { console.info('open fd failed err is' + err); }); -audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 +audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. ``` ### on('timeUpdate') on(type: 'timeUpdate', callback: Callback\): void -开始订阅音频播放[seek()](#seek)时间更新事件。 +Subscribes to the 'timeUpdate' event. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | ----------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 播放事件回调类型,支持的事件包括:'timeUpdate'。
- 'timeUpdate':[seek()](#seek)调用完成,触发该事件。 | -| callback | Callback\ | 是 | 播放事件回调方法。回调方法入参为成功seek的时间。 | +| type | string | Yes | Type of the event to subscribe to, which is 'timeUpdate' in this method.
The 'timeUpdate' event is triggered when the [seek()](#seek) method is called.| +| callback | Callback\ | Yes | Callback invoked when the event is triggered. The input parameter of the callback is the time when the seek operation is successful. | -**示例:** +**Example** ```js -audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调 +audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. if (typeof (seekDoneTime) == 'undefined') { console.info('audio seek fail'); return; } console.log('audio seek success. seekDoneTime: ' + seekDoneTime); }); -audioPlayer.seek(30000); //seek到30000ms的位置 +audioPlayer.seek(30000); // Seek to 30000 ms. ``` ### on('error') on(type: 'error', callback: ErrorCallback): void -开始订阅音频播放错误事件。 +Subscribes to the audio playback error event. -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 播放错误事件回调类型,支持的事件包括:'error'。
- 'error':音频播放中发生错误,触发该事件。 | -| callback | ErrorCallback | 是 | 播放错误事件回调方法。 | +| type | string | Yes | Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during audio playback.| +| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | -**示例:** +**Example** ```js -audioPlayer.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}`);//打印错误类型详细描述 +audioPlayer.on('error', (error) => { // Set the error event callback. + console.info(`audio error called, errName is ${error.name}`); // Print the error name. + console.info(`audio error called, errCode is ${error.code}`); // Print the error code. + console.info(`audio error called, errMessage is ${error.message}`);// Print the detailed description of the error type. }); -audioPlayer.setVolume(3); //设置volume为无效值,触发'error'事件 +audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. ``` ## AudioState -音频播放的状态机。可通过state属性获取当前状态。 +Enumerates the audio playback states. You can obtain the state through the **state** attribute. -| 名称 | 类型 | 描述 | +| Name | Type | Description | | ------------------ | ------ | ------------------------------------------------------------ | -| idle | string | 音频播放空闲。
**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer | -| playing | string | 音频正在播放。
**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer | -| paused | string | 音频暂停播放。
**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer | -| stopped | string | 音频播放停止。
**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer | -| error8+ | string | 错误状态。
**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer | +| idle | string | The audio player is idle.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| playing | string | Audio playback is in progress.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| paused | string | Audio playback is paused.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| stopped | string | Audio playback is stopped.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| +| error8+ | string | Audio playback is in the error state.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer| ## VideoPlayer8+ -视频播放管理类,用于管理和播放视频媒体。在调用VideoPlayer的方法前,需要先通过[createVideoPlayer()](#media.createvideoplayer8)构建一个[VideoPlayer](#videoplayer8)实例。 +Provides methods to manage and play video. Before calling a method of the **VideoPlayer** class, you must call [createVideoPlayer()](#media.createvideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. -视频播放demo可参考:[视频播放开发指导](../../media/video-playback.md) +For details about the video playback demo, see [Video Playback Development](../../media/video-playback.md). -### 属性 +### Attributes -| 名称 | 类型 | 可读 | 可写 | 说明 | +| Name | Type | Readable| Writable| Description | | ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| url8+ | string | 是 | 是 | 视频媒体URL,支持当前主流的视频格式(mp4、mpeg-ts、webm、mkv)。
**支持路径示例**:
1. fd类型播放:fd://xxx
![zh-cn_image_0000001164217678](figures/zh-cn_image_url.png)
**注意事项**:
使用媒体素材需要获取读权限,否则无法正常播放。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| loop8+ | boolean | 是 | 是 | 视频循环播放属性,设置为'true'表示循环播放。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| currentTime8+ | number | 是 | 否 | 视频的当前播放位置。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| duration8+ | number | 是 | 否 | 视频时长,返回-1表示直播模式。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| state8+ | [VideoPlayState](#videoplaystate8) | 是 | 否 | 视频播放的状态。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| width8+ | number | 是 | 否 | 视频宽。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| height8+ | number | 是 | 否 | 视频高。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | +| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xxx
![en-us_image_0000001164217678](figures/en-us_image_url.png)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| currentTime8+ | number | Yes | No | Current video playback position.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| duration8+ | number | Yes | No | Video duration. The value **-1** indicates the live streaming mode.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| state8+ | [VideoPlayState](#videoplaystate8) | Yes | No | Video playback state.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| width8+ | number | Yes | No | Video width.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| height8+ | number | Yes | No | Video height.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| ### setDisplaySurface8+ setDisplaySurface(surfaceId: string, callback: AsyncCallback\): void -通过回调方式设置SurfaceId。 +Sets **SurfaceId**. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | --------- | -------- | ---- | ------------------------- | -| surfaceId | string | 是 | SurfaceId | -| callback | function | 是 | 设置SurfaceId的回调方法。 | +| surfaceId | string | Yes | Surface ID to set. | +| callback | function | Yes | Callback used to set **SurfaceId**.| -**示例:** +**Example** ```js videoPlayer.setDisplaySurface(surfaceId, (err) => { @@ -696,23 +696,23 @@ videoPlayer.setDisplaySurface(surfaceId, (err) => { setDisplaySurface(surfaceId: string): Promise\ -通过Promise方式设置SurfaceId。 +Sets **SurfaceId**. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | --------- | ------ | ---- | --------- | -| surfaceId | string | 是 | SurfaceId | +| surfaceId | string | Yes | Surface ID to set.| -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | ------------- | ------------------------------ | -| Promise | 设置SurfaceId的Promise返回值。 | +| Promise | Promise used to set **SurfaceId**.| -**示例:** +**Example** ```js function failureCallback(error) { @@ -730,17 +730,17 @@ await videoPlayer.setDisplaySurface(surfaceId).then(() => { prepare(callback: AsyncCallback\): void -通过回调方式准备播放视频。 +Prepares for video playback. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------ | -| callback | function | 是 | 准备播放视频的回调方法。 | +| callback | function | Yes | Callback used to return the result.| -**示例:** +**Example** ```js videoPlayer.prepare((err) => { @@ -756,17 +756,17 @@ videoPlayer.prepare((err) => { prepare(): Promise\ -通过Promise方式准备播放视频。 +Prepares for video playback. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ----------------------------- | -| Promise\ | 准备播放视频的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js function failureCallback(error) { @@ -784,17 +784,17 @@ await videoPlayer.prepare().then(() => { play(callback: AsyncCallback\): void; -通过回调方式开始播放视频。 +Starts to play video resources. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------ | -| callback | function | 是 | 开始播放视频的回调方法。 | +| callback | function | Yes | Callback used to return the result.| -**示例:** +**Example** ```js videoPlayer.play((err) => { @@ -810,17 +810,17 @@ videoPlayer.play((err) => { play(): Promise\; -通过Promise方式开始播放视频。 +Starts to play video resources. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ----------------------------- | -| Promise\ | 开始播放视频的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js function failureCallback(error) { @@ -838,17 +838,17 @@ await videoPlayer.play().then(() => { pause(callback: AsyncCallback\): void -通过回调方式暂停播放视频。 +Pauses video playback. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------ | -| callback | function | 是 | 暂停播放视频的回调方法。 | +| callback | function | Yes | Callback used to return the result.| -**示例:** +**Example** ```js videoPlayer.pause((err) => { @@ -864,17 +864,17 @@ videoPlayer.pause((err) => { pause(): Promise\ -通过Promise方式暂停播放视频。 +Pauses video playback. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ----------------------------- | -| Promise\ | 暂停播放视频的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js function failureCallback(error) { @@ -892,17 +892,17 @@ await videoPlayer.pause().then(() => { stop(callback: AsyncCallback\): void -通过回调方式停止播放视频。 +Stops video playback. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------ | -| callback | function | 是 | 停止播放视频的回调方法。 | +| callback | function | Yes | Callback used to return the result.| -**示例:** +**Example** ```js videoPlayer.stop((err) => { @@ -918,17 +918,17 @@ videoPlayer.stop((err) => { stop(): Promise\ -通过Promise方式停止播放视频。 +Stops video playback. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ----------------------------- | -| Promise\ | 停止播放视频的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js function failureCallback(error) { @@ -946,17 +946,17 @@ await videoPlayer.stop().then(() => { reset(callback: AsyncCallback\): void -通过回调方式切换播放视频。 +Switches the video resource to be played. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------ | -| callback | function | 是 | 切换播放视频的回调方法。 | +| callback | function | Yes | Callback used to return the result.| -**示例:** +**Example** ```js videoPlayer.reset((err) => { @@ -972,17 +972,17 @@ videoPlayer.reset((err) => { reset(): Promise\ -通过Promise方式切换播放视频。 +Switches the video resource to be played. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ----------------------------- | -| Promise\ | 切换播放视频的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js function failureCallback(error) { @@ -1000,18 +1000,18 @@ await videoPlayer.reset().then(() => { seek(timeMs: number, callback: AsyncCallback\): void -通过回调方式跳转到指定播放位置,默认跳转到指定时间点的下一个关键帧。 +Seeks to the specified playback position. The next key frame at the specified position is played. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------ | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 | -| callback | function | 是 | 跳转到指定播放位置的回调方法。 | +| timeMs | number | Yes | Position to seek to, in milliseconds.| +| callback | function | Yes | Callback used to return the result.| -**示例:** +**Example** ```js videoPlayer.seek((seekTime, err) => { @@ -1027,19 +1027,19 @@ videoPlayer.seek((seekTime, err) => { seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\): void -通过回调方式跳转到指定播放位置。 +Seeks to the specified playback position. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ---------------------------------------- | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 | -| mode | SeekMode | 是 | 跳转模式,具体见[SeekMode](#seekmode8)。 | -| callback | function | 是 | 跳转到指定播放位置的回调方法。 | +| timeMs | number | Yes | Position to seek to, in milliseconds. | +| mode | SeekMode | Yes | Seek mode. For details, see [SeekMode](#seekmode8).| +| callback | function | Yes | Callback used to return the result. | -**示例:** +**Example** ```js videoPlayer.seek((seekTime, seekMode, err) => { @@ -1055,24 +1055,24 @@ videoPlayer.seek((seekTime, seekMode, err) => { seek(timeMs: number, mode?:SeekMode): Promise\ -通过Promise方式跳转到指定播放位置,如果没有设置mode则跳转到指定时间点的下一个关键帧。 +Seeks to the specified playback position. If **mode** is not specified, the next key frame at the specified position is played. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name| Type | Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒。 | -| mode | SeekMode | 否 | 跳转模式,具体见[SeekMode](#seekmode8) | +| timeMs | number | Yes | Position to seek to, in milliseconds. | +| mode | SeekMode | No | Seek mode. For details, see [SeekMode](#seekmode8).| -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ----------------------------------- | -| Promise\ | 跳转到指定播放位置的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js function failureCallback(error) { @@ -1081,7 +1081,7 @@ function failureCallback(error) { function catchCallback(error) { console.info(`video catchCallback, error:${error.message}`); } -await videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime表示seek完成后的时间点 +await videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime indicates the position after the seek operation is complete. console.info('seek success'); }, failureCallback).catch(catchCallback); @@ -1094,18 +1094,18 @@ await videoPlayer.seek(seekTime, seekMode).then((seekDoneTime) => { setVolume(vol: number, callback: AsyncCallback\): void -通过回调方式设置音量。 +Sets the volume. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 | -| callback | function | 是 | 设置音量的回调方法。 | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| +| callback | function | Yes | Callback used to return the result. | -**示例:** +**Example** ```js videoPlayer.setVolume((vol, err) => { @@ -1121,23 +1121,23 @@ videoPlayer.setVolume((vol, err) => { setVolume(vol: number): Promise\ -通过Promise方式设置音量。 +Sets the volume. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ------------------------- | -| Promise\ | 设置音量的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js function failureCallback(error) { @@ -1155,17 +1155,17 @@ await videoPlayer.setVolume(vol).then() => { release(callback: AsyncCallback\): void -通过回调方式释放视频资源。 +Releases the video playback resource. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------ | -| callback | function | 是 | 释放视频资源的回调方法。 | +| callback | function | Yes | Callback used to return the result.| -**示例:** +**Example** ```js videoPlayer.release((err) => { @@ -1181,17 +1181,17 @@ videoPlayer.release((err) => { release(): Promise\ -通过Promise方式释放视频资源。 +Releases the video playback resource. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ----------------------------- | -| Promise\ | 释放视频资源的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js function failureCallback(error) { @@ -1209,17 +1209,17 @@ await videoPlayer.release().then() => { getTrackDescription(callback: AsyncCallback>)>>): void -通过回调方式获取视频轨道信息。 +Obtains the video track information. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | -------------------------- | -| callback | function | 是 | 获取视频轨道信息回调方法。 | +| callback | function | Yes | Callback used to return the video track information obtained.| -**示例:** +**Example** ```js function printfDescription(obj) { @@ -1245,17 +1245,17 @@ videoPlayer.getTrackDescription((error, arrlist) => { getTrackDescription(): Promise>)>> -通过Promise方式获取视频轨道信息。 +Obtains the video track information. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------------------------------------------------- | ------------------------------- | -| Promise>)>> | 获取视频轨道信息Promise返回值。 | +| Promise>)>> | Promise used to return the video track information obtained.| -**示例:** +**Example** ```js function printfDescription(obj) { @@ -1289,18 +1289,18 @@ for (let i = 0; i < arrayDescription.length; i++) { setSpeed(speed:number, callback: AsyncCallback\): void -通过回调方式设置播放速度。 +Sets the video playback speed. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ---------------------------------------------------------- | -| speed | number | 是 | 指定播放视频速度,具体见[PlaybackSpeed](#playbackspeed8)。 | -| callback | function | 是 | 设置播放速度的回调方法。 | +| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| +| callback | function | Yes | Callback used to return the result. | -**示例:** +**Example** ```js videoPlayer.setSpeed((speed:number, err) => { @@ -1316,17 +1316,17 @@ videoPlayer.setSpeed((speed:number, err) => { setSpeed(speed:number): Promise\ -通过Promise方式设置播放速度。 +Sets the video playback speed. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------------------------------------- | -| speed | number | 是 | 指定播放视频速度,具体见[PlaybackSpeed](#playbackspeed8)。 | +| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| -**示例:** +**Example** ```js function failureCallback(error) { @@ -1344,18 +1344,18 @@ await videoPlayer.setSpeed(speed).then() => { on(type: 'playbackCompleted', callback: Callback\): void -开始监听视频播放完成事件。 +Subscribes to the video playback completion event. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ----------------------------------------------------------- | -| type | string | 是 | 视频播放完成事件回调类型,支持的事件:'playbackCompleted'。 | -| callback | function | 是 | 视频播放完成事件回调方法。 | +| type | string | Yes | Type of the event to subscribe to, which is 'playbackCompleted' in this example.| +| callback | function | Yes | Callback invoked when the event is triggered. | -**示例:** +**Example** ```js videoPlayer.on('playbackCompleted', () => { @@ -1367,18 +1367,18 @@ videoPlayer.on('playbackCompleted', () => { on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void -开始监听视频缓存更新事件。 +Subscribes to the video buffering update event. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 视频缓存事件回调类型,支持的事件:'bufferingUpdate'。 | -| callback | function | 是 | 视频缓存事件回调方法。
[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 | +| type | string | Yes | Type of the event to subscribe to, which is 'bufferingUpdate' in this example. | +| callback | function | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| -**示例:** +**Example** ```js videoPlayer.on('bufferingUpdate', (infoType, value) => { @@ -1391,18 +1391,18 @@ videoPlayer.on('bufferingUpdate', (infoType, value) => { on(type: 'startRenderFrame', callback: Callback\): void -开始监听视频播放首帧送显上报事件。 +Subscribes to the frame rendering start event. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 视频播放首帧送显上报事件回调类型,支持的事件:'startRenderFrame'。 | -| callback | function | 是 | 视频播放首帧送显上报事件回调方法。 | +| type | string | Yes | Type of the event to subscribe to, which is 'startRenderFrame' in this example.| +| callback | function | Yes | Callback invoked when the event is triggered. | -**示例:** +**Example** ```js videoPlayer.on('startRenderFrame', () => { @@ -1414,18 +1414,18 @@ videoPlayer.on('startRenderFrame', () => { on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void -开始监听视频播放宽高变化事件。 +Subscribes to the video width and height change event. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 视频播放宽高变化事件回调类型,支持的事件:'videoSizeChanged'。 | -| callback | function | 是 | 视频播放宽高变化事件回调方法,width表示宽,height表示高。 | +| type | string | Yes | Type of the event to subscribe to, which is 'videoSizeChanged' in this example.| +| callback | function | Yes | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height. | -**示例:** +**Example** ```js videoPlayer.on('videoSizeChanged', (width, height) => { @@ -1438,74 +1438,74 @@ videoPlayer.on('videoSizeChanged', (width, height) => { on(type: 'error', callback: ErrorCallback): void -开始监听视频播放错误事件。 +Subscribes to the video playback error event. -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 播放错误事件回调类型,支持的事件包括:'error'。
- 'error':视频播放中发生错误,触发该事件。 | -| callback | function | 是 | 播放错误事件回调方法。 | +| type | string | Yes | Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during video playback.| +| callback | function | Yes | Callback invoked when the event is triggered. | -**示例:** +**Example** ```js -videoPlayer.on('error', (error) => { // 设置'error'事件回调 - console.info(`video error called, errName is ${error.name}`); // 打印错误类型名称 - console.info(`video error called, errCode is ${error.code}`); // 打印错误码 - console.info(`video error called, errMessage is ${error.message}`);// 打印错误类型详细描述 +videoPlayer.on('error', (error) => { // Set the 'error' event callback. + console.info(`video error called, errName is ${error.name}`); // Print the error name. + console.info(`video error called, errCode is ${error.code}`); // Print the error code. + console.info(`video error called, errMessage is ${error.message}`);// Print the detailed description of the error type. }); -videoPlayer.setVolume(3); //设置volume为无效值,触发'error'事件 +videoPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. ``` ## VideoPlayState8+ -视频播放的状态机,可通过state属性获取当前状态。 +Enumerates the video playback states. You can obtain the state through the **state** attribute. -| 名称 | 类型 | 描述 | +| Name | Type | Description | | -------- | ------ | ------------------------------------------------------------ | -| idle | string | 视频播放空闲。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| prepared | string | 视频播放准备。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| playing | string | 视频正在播放。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| paused | string | 视频暂停播放。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| stopped | string | 视频播放停止。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| error | string | 错误状态。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | +| idle | string | The video player is idle.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| prepared | string | Video playback is being prepared.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| playing | string | Video playback is in progress.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| paused | string | Video playback is paused.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| stopped | string | Video playback is stopped.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| error | string | Video playback is in the error state.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| ## SeekMode8+ -视频播放的Seek模式枚举,可通过seek方法作为参数传递下去。 +Enumerates the video playback seek modes, which can be passed in the **seek** method. -| 名称 | 值 | 描述 | +| Name | Value | Description | | -------------- | ---- | ------------------------------------------------------------ | -| SEEK_NEXT_SYNC | 0 | 表示跳转到指定时间点的下一个关键帧,建议向后快进的时候用这个枚举值。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| SEEK_PREV_SYNC | 1 | 表示跳转到指定时间点的上一个关键帧,建议向前快进的时候用这个枚举值。
**系统能力:** SystemCapability.Multimedia.Media.Core | +| SEEK_NEXT_SYNC | 0 | Seeks to the next key frame at the specified position. You are advised to use this value for the rewind operation.
**System capability**: SystemCapability.Multimedia.Media.Core| +| SEEK_PREV_SYNC | 1 | Seeks to the previous key frame at the specified position. You are advised to use this value for the fast-forward operation.
**System capability**: SystemCapability.Multimedia.Media.Core| ## PlaybackSpeed8+ -视频播放的倍速枚举,可通过setSpeed方法作为参数传递下去。 +Enumerates the video playback speeds, which can be passed in the **setSpeed** method. -| 名称 | 值 | 描述 | +| Name | Value | Description | | -------------------- | ---- | ------------------------------------------------------------ | -| SPEED_FORWARD_0_75_X | 0 | 表示视频播放正常播速的0.75倍。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| SPEED_FORWARD_1_00_X | 1 | 表示视频播放正常播速。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| SPEED_FORWARD_1_25_X | 2 | 表示视频播放正常播速的1.25倍。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| SPEED_FORWARD_1_75_X | 3 | 表示视频播放正常播速的1.75倍。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | -| SPEED_FORWARD_2_00_X | 4 | 表示视频播放正常播速的2.00倍。
**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer | +| SPEED_FORWARD_0_75_X | 0 | Plays the video at 0.75 times the normal speed.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| SPEED_FORWARD_1_00_X | 1 | Plays the video at the normal speed.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| SPEED_FORWARD_1_25_X | 2 | Plays the video at 1.25 times the normal speed.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| SPEED_FORWARD_1_75_X | 3 | Plays the video at 1.75 times the normal speed.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| +| SPEED_FORWARD_2_00_X | 4 | Plays the video at 2.00 times the normal speed.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer| ## MediaDescription8+ ### [key : string] : any -通过key-value方式获取媒体信息。 +Defines media information in key-value mode. -| 名称 | 类型 | 说明 | +| Name | Type | Description | | ----- | ------ | ------------------------------------------------------------ | -| key | string | 通过key值获取对应的value。key值具体可见[MediaDescriptionKey](#mediadescriptionkey8)。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| value | any | 对应key值得value。其类型可为任意类型,具体key对应value的类型可参考[MediaDescriptionKey](#mediadescriptionkey8)的描述信息。
**系统能力:** SystemCapability.Multimedia.Media.Core | +| key | string | Key of the media information. For details about the keys, see [MediaDescriptionKey](#mediadescriptionkey8).
**System capability**: SystemCapability.Multimedia.Media.Core| +| value | any | Value of the key. For details about the values, see [MediaDescriptionKey](#mediadescriptionkey8).
**System capability**: SystemCapability.Multimedia.Media.Core| -**示例:** +**Example** ```js function printfItemDescription(obj, key) { @@ -1517,7 +1517,7 @@ function printfItemDescription(obj, key) { audioPlayer.getTrackDescription((error, arrlist) => { if (typeof (arrlist) != 'undefined') { for (let i = 0; i < arrlist.length; i++) { - printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE); //打印出每条轨道MD_KEY_TRACK_TYPE的值 + printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. } } else { console.log(`audio getTrackDescription fail, error:${error.message}`); @@ -1527,27 +1527,27 @@ audioPlayer.getTrackDescription((error, arrlist) => { ## AudioRecorder -音频录制管理类,用于录制音频媒体。在调用AudioRecorder的方法前,需要先通过[createAudioRecorder()](#media.createaudiorecorder) 构建一个[AudioRecorder](#audiorecorder)实例。 +Implements audio recording. Before calling a method of the **AudioRecorder** class, you must call [createAudioRecorder()](#media.createaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. -音频录制demo可参考:[音频录制开发指导](../../media/audio-recorder.md) +For details about the audio recording demo, see [Audio Recording Development](../../media/audio-recorder.md). ### prepare prepare(config: AudioRecorderConfig): void -录音准备。 +Prepares for recording. -**需要权限:** ohos.permission.MICROPHONE +**Required permissions:** ohos.permission.MICROPHONE -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name| Type | Mandatory| Description | | ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| config | [AudioRecorderConfig](#audiorecorderconfig) | 是 | 配置录音的相关参数,包括音频输出URI、[编码格式](#audioencoder)、采样率、声道数、[输出格式](#audiooutputformat)等。 | +| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Audio recording parameters, including the audio output URI, [encoding format](#audioencoder), sampling rate, number of audio channels, and [output format](#audiooutputformat).| -**示例:** +**Example** ```js let audioRecorderConfig = { @@ -1556,10 +1556,10 @@ let audioRecorderConfig = { audioSampleRate : 22050, numberOfChannels : 2, format : media.AudioOutputFormat.AAC_ADTS, - uri : 'fd://1', // 文件需先由调用者创建,并给予适当的权限 + uri : 'fd://1', // The file must be created by the caller and granted with proper permissions. location : { latitude : 30, longitude : 130}, } -audioRecorder.on('prepare', () => { //设置'prepare'事件回调 +audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. console.log('prepare success'); }); audioRecorder.prepare(audioRecorderConfig); @@ -1570,14 +1570,14 @@ audioRecorder.prepare(audioRecorderConfig); start(): void -开始录制,需在[prepare](#audiorecorder_on)事件成功触发后,才能调用start方法。 +Starts audio recording. This method can be called only after the [prepare](#audiorecorder_on) event is triggered. -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder -**示例:** +**Example** ```js -audioRecorder.on('start', () => { //设置'start'事件回调 +audioRecorder.on('start', () => { // Set the 'start' event callback. console.log('audio recorder start success'); }); audioRecorder.start(); @@ -1587,14 +1587,14 @@ audioRecorder.start(); pause():void -暂停录制,需要在[start](#audiorecorder_on)事件成功触发后,才能调用pause方法。 +Pauses audio recording. This method can be called only after the [start](#audiorecorder_on) event is triggered. -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder -**示例:** +**Example** ```js -audioRecorder.on('pause', () => { //设置'pause'事件回调 +audioRecorder.on('pause', () => { // Set the 'pause' event callback. console.log('audio recorder pause success'); }); audioRecorder.pause(); @@ -1604,14 +1604,14 @@ audioRecorder.pause(); resume():void -暂停录制,需要在[pause](#audiorecorder_on)事件成功触发后,才能调用resume方法。 +Resumes audio recording. This method can be called only after the [pause](#audiorecorder_on) event is triggered. -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder -**示例:** +**Example** ```js -audioRecorder.on('resume', () => { //设置'resume'事件回调 +audioRecorder.on('resume', () => { // Set the 'resume' event callback. console.log('audio recorder resume success'); }); audioRecorder.resume(); @@ -1621,14 +1621,14 @@ audioRecorder.resume(); stop(): void -停止录音。 +Stops audio recording. -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder -**示例:** +**Example** ```js -audioRecorder.on('stop', () => { //设置'stop'事件回调 +audioRecorder.on('stop', () => { // Set the 'stop' event callback. console.log('audio recorder stop success'); }); audioRecorder.stop(); @@ -1638,14 +1638,14 @@ audioRecorder.stop(); release(): void -释放录音资源。 +Releases the audio recording resource. -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder -**示例:** +**Example** ```js -audioRecorder.on('release', () => { //设置'release'事件回调 +audioRecorder.on('release', () => { // Set the 'release' event callback. console.log('audio recorder release success'); }); audioRecorder.release(); @@ -1656,16 +1656,16 @@ audioRecorder = undefined; reset(): void -重置录音。 +Resets audio recording. -进行重置录音之前,需要先调用[stop()](#audiorecorder_stop)停止录音。重置录音之后,需要调用[prepare()](#audiorecorder_prepare)设置录音参数项,才能再次进行录音。 +Before resetting audio recording, you must call [stop()](#audiorecorder_stop) to stop recording. After audio recording is reset, you must call [prepare()](#audiorecorder_prepare) to set the recording parameters for another recording. -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder -**示例:** +**Example** ```js -audioRecorder.on('reset', () => { //设置'reset'事件回调 +audioRecorder.on('reset', () => { // Set the 'reset' event callback. console.log('audio recorder reset success'); }); audioRecorder.reset(); @@ -1675,156 +1675,156 @@ audioRecorder.reset(); on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void -开始订阅音频录制事件。 +Subscribes to the audio recording events. -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 录制事件回调类型,支持的事件包括:'prepare' \| 'start' \| 'pause' \| ’resume‘ \| 'stop' \| 'release' \| 'reset'。
- 'prepare' :完成[prepare](#audiorecorder_prepare)调用,音频录制参数设置完成,触发该事件。
- 'start' :完成[start](#audiorecorder_start)调用,音频录制开始,触发该事件。
- 'pause': 完成[pause](#audiorecorder_pause)调用,音频暂停录制,触发该事件。
- 'resume': 完成[resume](#audiorecorder_resume)调用,音频恢复录制,触发该事件。
- 'stop' :完成[stop](#audiorecorder_stop)调用,音频停止录制,触发该事件。
- 'release' :完成[release](#audiorecorder_release)调用,音频释放录制资源,触发该事件。
- 'reset':完成[reset](#audiorecorder_reset)调用,音频重置为初始状态,触发该事件。 | -| callback | ()=>void | 是 | 录制事件回调方法。 | +| type | string | Yes | Type of the event to subscribe to. The following events are supported: 'prepare'\|'start'\| 'pause' \| 'resume' \|'stop'\|'release'\|'reset'
- The 'prepare' event is triggered when the [prepare](#audiorecorder_prepare) method is called and the audio recording parameters are set.
- The 'start' event is triggered when the [start](#audiorecorder_start) method is called and audio recording starts.
- The 'pause' event is triggered when the [pause](#audiorecorder_pause) method is called and audio recording is paused.
- The 'resume' event is triggered when the [resume](#audiorecorder_resume) method is called and audio recording is resumed.
- The 'stop' event is triggered when the [stop](#audiorecorder_stop) method is called and audio recording stops.
- The 'release' event is triggered when the [release](#audiorecorder_release) method is called and the recording resource is released.
- The 'reset' event is triggered when the [reset](#audiorecorder_reset) method is called and audio recording is reset.| +| callback | ()=>void | Yes | Callback invoked when the event is triggered. | -**示例:** +**Example** ```js -let audiorecorder = media.createAudioRecorder(); // 创建一个音频录制实例 +let audiorecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. let audioRecorderConfig = { audioEncoder : media.AudioEncoder.AAC_LC, , audioEncodeBitRate : 22050, audioSampleRate : 22050, numberOfChannels : 2, format : media.AudioOutputFormat.AAC_ADTS, - uri : 'fd://xx', // 文件需先由调用者创建,并给予适当的权限 + uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. location : { latitude : 30, longitude : 130}, } -audioRecorder.on('error', (error) => { // 设置'error'事件回调 +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}`); }); -audioRecorder.on('prepare', () => { // 设置'prepare'事件回调 +audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. console.log('prepare success'); - audioRecorder.start(); // 开始录制,并触发'start'事件回调 + audioRecorder.start(); // Start recording and trigger the 'start' event callback. }); -audioRecorder.on('start', () => { // 设置'start'事件回调 +audioRecorder.on('start', () => { // Set the 'start' event callback. console.log('audio recorder start success'); }); -audioRecorder.on('pause', () => { // 设置'pause'事件回调 +audioRecorder.on('pause', () => { // Set the 'pause' event callback. console.log('audio recorder pause success'); }); -audioRecorder.on('resume', () => { // 设置'resume'事件回调 +audioRecorder.on('resume', () => { // Set the 'resume' event callback. console.log('audio recorder resume success'); }); -audioRecorder.on('stop', () => { // 设置'stop'事件回调 +audioRecorder.on('stop', () => { // Set the 'stop' event callback. console.log('audio recorder stop success'); }); -audioRecorder.on('release', () => { // 设置'release'事件回调 +audioRecorder.on('release', () => { // Set the 'release' event callback. console.log('audio recorder release success'); }); -audioRecorder.on('reset', () => { // 设置'reset'事件回调 +audioRecorder.on('reset', () => { // Set the 'reset' event callback. console.log('audio recorder reset success'); }); -audioRecorder.prepare(audioRecorderConfig) // 设置录制参数 ,并触发'prepare'事件回调 +audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. ``` ### on('error') on(type: 'error', callback: ErrorCallback): void -开始订阅音频录制错误事件。 +Subscribes to the audio recording error event. -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 录制错误事件回调类型'error'。
- 'error':音频录制过程中发生错误,触发该事件。 | -| callback | ErrorCallback | 是 | 录制错误事件回调方法。 | +| type | string | Yes | Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during audio recording.| +| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | -**示例:** +**Example** ```js -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}`); // 打印错误类型详细描述 +audioRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); // Print the error name. + console.info(`audio error called, errCode is ${error.code}`); // Print the error code. + console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. }); -audioRecorder.prepare(); // prepare不设置参数,触发'error'事件 +audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. ``` ## AudioRecorderConfig -表示音频的录音配置。 +Describes audio recording configurations. -| 名称 | 参数类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | --------------------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| audioEncoder | [AudioEncoder](#audioencoder) | 否 | 音频编码格式,默认设置为AAC_LC。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| audioEncodeBitRate | number | 否 | 音频编码比特率,默认值为48000。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| audioSampleRate | number | 否 | 音频采集采样率,默认值为48000。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| numberOfChannels | number | 否 | 音频采集声道数,默认值为2。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| format | [AudioOutputFormat](#audiooutputformat) | 否 | 音量输出封装格式,默认设置为MPEG_4。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| location8+ | [Location](#location8) | 否 | 音频采集的地理位置。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| uri | string | 是 | 视频输出URI:fd://xx (fd number)
![zh-cn_image_0000001164217678](figures/zh-cn_image_url.png)
文件需要由调用者创建,并赋予适当的权限。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | +| audioEncoder | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| audioEncodeBitRate | number | No | Audio encoding bit rate. The default value is **48000**.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| audioSampleRate | number | No | Audio sampling rate. The default value is **48000**.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| numberOfChannels | number | No | Number of audio channels. The default value is **2**.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| format | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| location8+ | [Location](#location8) | No | Geographical location of the recorded audio.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| ## AudioEncoder -表示音频编码格式的枚举。 +Enumerates the audio encoding formats. -| 名称 | 默认值 | 说明 | +| Name | Default Value| Description | | ------- | ------ | ------------------------------------------------------------ | -| DEFAULT | 0 | Default audio encoding format is AMR_NB。
本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| AMR_NB | 1 | AMR-NB(Adaptive Multi Rate-Narrow Band Speech Codec) 编码格式。
本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| AMR_WB | 2 | AMR-WB(Adaptive Multi Rate-Wide Band Speech Codec) 编码格式。
本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| AAC_LC | 3 | AAC-LC(Advanced Audio Coding Low Complexity)编码格式。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| HE_AAC | 4 | HE_AAC(High-Efficiency Advanced Audio Coding)编码格式。
本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | +| DEFAULT | 0 | Default audio encoding format, which is Adaptive Multi Rate-Narrow Band Speech Codec (AMR-NB).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AMR_NB | 1 | AMR-NB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| ## AudioOutputFormat -表示音频封装格式的枚举。 +Enumerates the audio output formats. -| 名称 | 默认值 | 说明 | +| Name | Default Value| Description | | -------- | ------ | ------------------------------------------------------------ | -| DEFAULT | 0 | 默认封装格式为MPEG-4。
本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| MPEG_4 | 2 | 封装为MPEG-4格式。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| AMR_NB | 3 | 封装为AMR_NB格式。
本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| AMR_WB | 4 | 封装为AMR_WB格式。
本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | -| AAC_ADTS | 6 | 封装为ADTS(Audio Data Transport Stream)格式,是AAC音频的传输流格式。
**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder | +| DEFAULT | 0 | Default encapsulation format, which is MPEG-4.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| MPEG_4 | 2 | MPEG-4.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AMR_NB | 3 | AMR_NB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AMR_WB | 4 | AMR_WB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| +| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.
**System capability**: SystemCapability.Multimedia.Media.AudioRecorder| ## VideoRecorder8+ -视频录制管理类,用于录制视频媒体。在调用VideoRecorder的方法前,需要先通过[createVideoRecorder()](#media.createvideorecorder8)构建一个[VideoRecorder](#videorecorder8)实例。 +Implements video recording. Before calling a method of the **VideoRecorder** class, you must call [createVideoRecorder()](#media.createvideorecorder8) to create a [VideoRecorder](#videorecorder8) instance. -视频录制demo可参考:[视频录制开发指导](../../media/video-recorder.md) +For details about the video recording demo, see [Video Recording Development](../../media/video-recorder.md). -### 属性 +### Attributes -| 名称 | 类型 | 可读 | 可写 | 说明 | +| Name | Type | Readable| Writable| Description | | ------------------ | ------------------------------------- | ---- | ---- | ---------------- | -| state8+ | [VideoRecordState](#videorecordstate) | 是 | 否 | 视频录制的状态。 | +| state8+ | [VideoRecordState](#videorecordstate) | Yes | No | Video recording state.| ### prepare8+ prepare(config: VideoRecorderConfig, callback: AsyncCallback\): void; -异步方式进行视频录制的参数设置。通过注册回调函数获取返回值。 +Sets video recording parameters in asynchronous mode. This API uses a callback to return the result. -**需要权限:** ohos.permission.MICROPHONE ohos.permission.CAMERA +**Required permissions:** ohos.permission.MICROPHONE ohos.permission.CAMERA -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ----------------------------------- | -| config | [VideoRecorderConfig](#videorecorderconfig) | 是 | 配置视频录制的相关参数。 | -| callback | AsyncCallback\ | 是 | 异步视频录制prepare方法的回调方法。 | +| config | [VideoRecorderConfig](#videorecorderconfig) | Yes | Video recording parameters to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**示例:** +**Example** ```js let videoProfile = { @@ -1844,7 +1844,7 @@ let videoConfig = { audioSourceType : 1, videoSourceType : 0, profile : videoProfile, - url : 'fd://xx', // 文件需先由调用者创建,并给予适当的权限 + url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. orientationHint : 0, location : { latitude : 30, longitude : 130 }, } @@ -1868,7 +1868,7 @@ media.createVideoRecorder((err, recorder) => { if (typeof (err) == 'undefined' && typeof (recorder) != 'undefined') { videoRecorder = recorder; console.info('createVideoRecorder success'); - eventEmitter.emit('prepare'); // prepare事件触发 + eventEmitter.emit('prepare'); // Trigger the 'prepare' event. } else { console.info('createVideoRecorder failed and error is ' + err.message); } @@ -1879,25 +1879,25 @@ media.createVideoRecorder((err, recorder) => { prepare(config: VideoRecorderConfig): Promise\; -异步方式进行视频录制的参数设置。通过Promise获取返回值。 +Sets video recording parameters in asynchronous mode. This API uses a promise to return the result. -**需要权限:** ohos.permission.MICROPHONE ohos.permission.CAMERA +**Required permissions:** ohos.permission.MICROPHONE ohos.permission.CAMERA -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name| Type | Mandatory| Description | | ------ | ------------------------------------------- | ---- | ------------------------ | -| config | [VideoRecorderConfig](#videorecorderconfig) | 是 | 配置视频录制的相关参数。 | +| config | [VideoRecorderConfig](#videorecorderconfig) | Yes | Video recording parameters to set.| -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ---------------------------------------- | -| Promise\ | 异步视频录制prepare方法的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js let videoProfile = { @@ -1917,7 +1917,7 @@ let videoConfig = { audioSourceType : 1, videoSourceType : 0, profile : videoProfile, - url : 'fd://xx', // 文件需先由调用者创建,并给予适当的权限 + url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. orientationHint : 0, location : { latitude : 30, longitude : 130 }, } @@ -1950,25 +1950,25 @@ await videoRecorder.prepare(videoConfig).then(() => { getInputSurface(callback: AsyncCallback\): void; -异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的数据。 +Obtains the surface required for recording in asynchronous mode. This surface is provided for the caller. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data. -应当注意,填入的视频数据需要携带时间戳(单位ns),buffersize。时间戳的起始时间请以系统启动时间为基准。 +Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp is based on the system startup time. -只能在[prepare()](#videorecorder_prepare1)接口调用后调用。 +This method can be called only after [prepare()](#videorecorder_prepare1) is called. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | --------------------------- | -| callback | AsyncCallback\ | 是 | 异步获得surface的回调方法。 | +| callback | AsyncCallback\ | Yes | Callback used to obtain the result.| -**示例:** +**Example** ```js // asyncallback -let surfaceID = null; // 传递给外界的surfaceID +let surfaceID = null; // Surface ID passed to the external system. videoRecorder.getInputSurface((err, surfaceId) => { if (typeof (err) == 'undefined') { console.info('getInputSurface success'); @@ -1983,25 +1983,25 @@ videoRecorder.getInputSurface((err, surfaceId) => { getInputSurface(): Promise\; - 异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的数据。 + Obtains the surface required for recording in asynchronous mode. This surface is provided for the caller. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data. -应当注意,填入的视频数据需要携带时间戳(单位ns),buffersize。时间戳的起始时间请以系统启动时间为基准。 +Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp is based on the system startup time. -只能在[prepare()](#videorecorder_prepare1)接口调用后调用。 +This method can be called only after [prepare()](#videorecorder_prepare1) is called. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | ---------------- | -------------------------------- | -| Promise\ | 异步获得surface的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js // promise -let surfaceID = null; // 传递给外界的surfaceID +let surfaceID = null; // Surface ID passed to the external system. await videoRecorder.getInputSurface().then((surfaceId) => { console.info('getInputSurface success'); surfaceID = surfaceId; @@ -2016,19 +2016,19 @@ await videoRecorder.getInputSurface().then((surfaceId) => { start(callback: AsyncCallback\): void; -异步方式开始视频录制。通过注册回调函数获取返回值。 +Starts video recording in asynchronous mode. This API uses a callback to return the result. -在[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface8)后调用,需要依赖数据源先给surface传递数据。 +This method can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步开始视频录制的回调方法。 | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**示例:** +**Example** ```js // asyncallback @@ -2045,19 +2045,19 @@ videoRecorder.start((err) => { start(): Promise\; -异步方式开始视频录制。通过Promise获取返回值。 +Starts video recording in asynchronous mode. This API uses a promise to return the result. -在[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface8)后调用,需要依赖数据源先给surface传递数据。 +This method can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ------------------------------------- | -| Promise\ | 异步开始视频录制方法的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js // promise @@ -2074,19 +2074,19 @@ await videoRecorder.start().then(() => { pause(callback: AsyncCallback\): void; -异步方式暂停视频录制。通过注册回调函数获取返回值。 +Pauses video recording in asynchronous mode. This API uses a callback to return the result. -在[start()](#videorecorder_start1)后调用。可以通过调用[resume()](#videorecorder_resume1)接口来恢复录制。 +This method can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步暂停视频录制的回调方法。 | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**示例:** +**Example** ```js // asyncallback @@ -2103,19 +2103,19 @@ videoRecorder.pause((err) => { pause(): Promise\; -异步方式暂停视频录制。通过Promise获取返回值。 +Pauses video recording in asynchronous mode. This API uses a promise to return the result. -在[start()](#videorecorder_start1)后调用。可以通过调用[resume()](#videorecorder_resume1)接口来恢复录制。 +This method can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ------------------------------------- | -| Promise\ | 异步暂停视频录制方法的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js // promise @@ -2132,17 +2132,17 @@ await videoRecorder.pause().then(() => { resume(callback: AsyncCallback\): void; -异步方式恢复视频录制。通过注册回调函数获取返回值。 +Resumes video recording in asynchronous mode. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步恢复视频录制的回调方法。 | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**示例:** +**Example** ```js // asyncallback @@ -2159,17 +2159,17 @@ videoRecorder.resume((err) => { resume(): Promise\; -异步方式恢复视频录制。通过Promise获取返回值。 +Resumes video recording in asynchronous mode. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ------------------------------------- | -| Promise\ | 异步恢复视频录制方法的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js // promise @@ -2186,19 +2186,19 @@ await videoRecorder.resume().then(() => { stop(callback: AsyncCallback\): void; -异步方式停止视频录制。通过注册回调函数获取返回值。 +Stops video recording in asynchronous mode. This API uses a callback to return the result. -需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface8)接口才能重新录制。 +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步停止视频录制的回调方法。 | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**示例:** +**Example** ```js // asyncallback @@ -2215,19 +2215,19 @@ videoRecorder.stop((err) => { stop(): Promise\; -异步方式停止视频录制。通过Promise获取返回值。 +Stops video recording in asynchronous mode. This API uses a promise to return the result. -需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface8)接口才能重新录制。 +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ------------------------------------- | -| Promise\ | 异步停止视频录制方法的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js // promise @@ -2244,17 +2244,17 @@ await videoRecorder.stop().then(() => { release(callback: AsyncCallback\): void; -异步方式释放视频录制资源。通过注册回调函数获取返回值。 +Releases the video recording resource in asynchronous mode. This API uses a callback to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | -------------------------------- | -| callback | AsyncCallback\ | 是 | 异步释放视频录制资源的回调方法。 | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**示例:** +**Example** ```js // asyncallback @@ -2271,17 +2271,17 @@ videoRecorder.release((err) => { release(): Promise\; -异步方式释放视频录制资源。通过Promise获取返回值。 +Releases the video recording resource in asynchronous mode. This API uses a promise to return the result. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ----------------------------------------- | -| Promise\ | 异步释放视频录制资源方法的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js // promise @@ -2298,19 +2298,19 @@ await videoRecorder.release().then(() => { reset(callback: AsyncCallback\): void; -异步方式重置视频录制。通过注册回调函数获取返回值。 +Resets video recording in asynchronous mode. This API uses a callback to return the result. -需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface8)接口才能重新录制。 +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步重置视频录制的回调方法。 | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**示例:** +**Example** ```js // asyncallback @@ -2327,19 +2327,19 @@ videoRecorder.reset((err) => { reset(): Promise\; -异步方式重置视频录制。通过Promise获取返回值。 +Resets video recording in asynchronous mode. This API uses a promise to return the result. -需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface8)接口才能重新录制。 +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**返回值:** +**Return value** -| 类型 | 说明 | +| Type | Description | | -------------- | ------------------------------------- | -| Promise\ | 异步重置视频录制方法的Promise返回值。 | +| Promise\ | Promise used to return the result.| -**示例:** +**Example** ```js // promise @@ -2356,101 +2356,101 @@ await videoRecorder.reset().then(() => { on(type: 'error', callback: ErrorCallback): void -开始订阅视频录制错误事件。 +Subscribes to the video recording error event. -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder -**参数:** +**Parameters** -| 参数名 | 类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 录制错误事件回调类型'error'。
- 'error':音频录制过程中发生错误,触发该事件。 | -| callback | ErrorCallback | 是 | 录制错误事件回调方法。 | +| type | string | Yes | Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during video recording.| +| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | -**示例:** +**Example** ```js -videoRecorder.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}`); // 打印错误类型详细描述 +videoRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); // Print the error name. + console.info(`audio error called, errCode is ${error.code}`); // Print the error code. + console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. }); -// 当获取videoRecordState接口出错时通过此订阅事件上报 +// This event is reported when an error occurs during the retrieval of videoRecordState. ``` ## VideoRecordState8+ -视频录制的状态机。可通过state属性获取当前状态。 +Enumerates the video recording states. You can obtain the state through the **state** attribute. -| 名称 | 类型 | 描述 | +| Name | Type | Description | | -------- | ------ | ------------------------------------------------------------ | -| idle | string | 视频录制空闲。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| prepared | string | 视频录制参数设置完成。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| playing | string | 视频正在录制。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| paused | string | 视频暂停录制。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| stopped | string | 视频录制停止。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| error | string | 错误状态。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | +| idle | string | The video recorder is idle.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| prepared | string | The video recording parameters are set.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| playing | string | Video recording is in progress.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| paused | string | Video recording is paused.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| stopped | string | Video recording is stopped.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| error | string | Video recording is in the error state.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| ## VideoRecorderConfig8+ -表示视频录制的参数设置。 +Describes the video recording parameters. -| 名称 | 参数类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | --------------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| audioSourceType | [AudioSourceType](#audiosourcetype8+) | 是 | 视频录制的音频源类型。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| videoSourceType | [VideoSourceType](#videosourcetype8+) | 是 | 视频录制的视频源类型。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| profile | [VideoRecorderProfile](#videorecorderprofile8+) | 是 | 视频录制的profile。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| orientationHint | number | 否 | 录制视频的旋转角度。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| location | [Location](#location8) | 否 | 录制视频的地理位置。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| url | string | 是 | 视频输出URL:fd://xx (fd number)
![zh-cn_image_0000001164217678](figures/zh-cn_image_url.png)
文件需要由调用者创建,并赋予适当的权限。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | +| audioSourceType | [AudioSourceType](#audiosourcetype8+) | Yes | Type of the audio source for video recording.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| videoSourceType | [VideoSourceType](#videosourcetype8+) | Yes | Type of the video source for video recording.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| profile | [VideoRecorderProfile](#videorecorderprofile8+) | Yes | Video recording profile.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| orientationHint | number | No | Rotation angle of the recorded video.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| location | [Location](#location8) | No | Geographical location of the recorded video.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| ## AudioSourceType8+ -表示视频录制中音频源类型的枚举。 +Enumerates the audio source types for video recording. -| 名称 | 值 | 说明 | +| Name | Value | Description | | ------------------------- | ---- | ------------------------------------------------------------ | -| AUDIO_SOURCE_TYPE_DEFAULT | 0 | 默认的音频输入源类型。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| AUDIO_SOURCE_TYPE_MIC | 1 | 表示MIC的音频输入源。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | +| AUDIO_SOURCE_TYPE_DEFAULT | 0 | Default audio input source.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| AUDIO_SOURCE_TYPE_MIC | 1 | Mic audio input source.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| ## VideoSourceType8+ -表示视频录制中视频源类型的枚举。 +Enumerates the video source types for video recording. -| 名称 | 值 | 说明 | +| Name | Value | Description | | ----------------------------- | ---- | ------------------------------------------------------------ | -| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | 输入surface中携带的是raw data。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | 输入surface中携带的是ES data。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | +| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | The input surface carries raw data.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | The input surface carries ES data.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| ## VideoRecorderProfile8+ -视频录制的配置文件。 +Describes the video recording profile. -| 名称 | 参数类型 | 必填 | 说明 | +| Name | Type | Mandatory| Description | | ---------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| audioBitrate | number | 是 | 音频编码比特率。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| audioChannels | number | 是 | 音频采集声道数。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| audioCodec | [CodecMimeType](#CodecMimeType8) | 是 | 音频编码格式。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| audioSampleRate | number | 是 | 音频采样率。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| fileFormat | [ContainerFormatType](#containerformattype8) | 是 | 文件的容器格式。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| videoCodec | [CodecMimeType](#CodecMimeType8) | 是 | 视频编码格式。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| videoFrameWidth | number | 是 | 录制视频帧的宽。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | -| videoFrameHeight | number | 是 | 录制视频帧的高。
**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder | +| audioBitrate | number | Yes | Audio encoding bit rate.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| audioChannels | number | Yes | Number of audio channels.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| audioCodec | [CodecMimeType](#CodecMimeType8) | Yes | Audio encoding format.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| audioSampleRate | number | Yes | Audio sampling rate.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| fileFormat | [ContainerFormatType](#containerformattype8) | Yes | Container format of a file.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| videoCodec | [CodecMimeType](#CodecMimeType8) | Yes | Video encoding format.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| videoFrameWidth | number | Yes | Width of the recorded video frame.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| +| videoFrameHeight | number | Yes | Height of the recorded video frame.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder| ## ContainerFormatType8+ -表示容器格式类型的枚举,缩写为CFT。 +Enumerates the container format types (CFTs). -| 名称 | 值 | 说明 | +| Name | Value | Description | | ----------- | ----- | ------------------------------------------------------------ | -| CFT_MPEG_4 | "mp4" | 视频的容器格式,MP4。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| CFT_MPEG_4A | "m4a" | 音频的容器格式,M4A。
**系统能力:** SystemCapability.Multimedia.Media.Core | +| CFT_MPEG_4 | "mp4" | Video container format MP4.
**System capability**: SystemCapability.Multimedia.Media.Core| +| CFT_MPEG_4A | "m4a" | Audio container format M4A.
**System capability**: SystemCapability.Multimedia.Media.Core| ## Location8+ -视频录制的地理位置。 +Describes the geographical location of the recorded video. -| 名称 | 参数类型 | 必填 | 说明 | +| Name | Type| Mandatory| Description | | --------- | -------- | ---- | ------------------------------------------------------------ | -| latitude | number | 是 | 地理位置的纬度。
**系统能力:** SystemCapability.Multimedia.Media.Core | -| longitude | number | 是 | 地理位置的经度。
**系统能力:** SystemCapability.Multimedia.Media.Core | \ No newline at end of file +| latitude | number | Yes | Latitude of the geographical location.
**System capability**: SystemCapability.Multimedia.Media.Core| +| longitude | number | Yes | Longitude of the geographical location.
**System capability**: SystemCapability.Multimedia.Media.Core| -- Gitee From 2af045609defcd471cdbf3ff9986a20b9498b68d Mon Sep 17 00:00:00 2001 From: wusongqing Date: Wed, 16 Mar 2022 19:58:49 +0800 Subject: [PATCH 4/4] updated english docs Signed-off-by: wusongqing --- en/application-dev/media/video-playback.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/application-dev/media/video-playback.md b/en/application-dev/media/video-playback.md index d15b8f22e0f..29a31dcc5f1 100644 --- a/en/application-dev/media/video-playback.md +++ b/en/application-dev/media/video-playback.md @@ -28,7 +28,7 @@ For details about the APIs used for video playback, see [js-apis-media.md](../re The full video playback process includes creating an instance, setting the URL, setting the surface ID, preparing for video playback, playing video, pausing playback, obtaining track information, seeking to a playback position, setting the volume, setting the playback speed, stopping playback, resetting the playback configuration, and releasing resources. -For details about the **url** media source input types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_Attributes). +For details about the **url** media source input types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_attributes). For details about how to create an Xcomponent, see [Xcomponent Creation](#Xcomponent). -- Gitee