提交 78f1f7a9 编写于 作者: W wusongqing

updated docs

Signed-off-by: Nwusongqing <wusongqing@huawei.com>
上级 be5bdb7e
...@@ -2,127 +2,178 @@ ...@@ -2,127 +2,178 @@
## When to Use ## When to Use
You use audio playback APIs to convert audio data into audible analog signals, play the audio signals using output devices, and manage playback tasks. You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks.
**Figure 1** Playback status **Figure 1** Playback status
![](figures/playback-status.png "playback-status")
![en-us_image_20220117](figures/en-us_image_20220117.jpg)
## Available APIs ## How to Develop
**Table 1** APIs for audio playback For details about the APIs used for audio playback, see [js-apis-media.md](../reference/apis/js-apis-media.md).
| API| Description| ### Full-Process Scenario
| -------- | -------- |
| media.createAudioPlayer() | Creates an **AudioPlayer** instance.| 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 | Provides audio playback features. For details, see the table below.|
For details about the **src** media source input types supported by **AudioPlayer**, see the [src attributes](../reference/apis/js-apis-media.md#audioplayer_Attributes).
**Table 2** AudioPlayer methods
```js
| Method| Description| function SetCallBack(audioPlayer) {
| -------- | -------- | audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
| release() | Releases audio resources.| console.info('audio set source success');
| play() | Starts audio playback.| // The playback page is ready. You can click the Play button to start the playback.
| pause() | Pauses playback.| });
| stop() | Stops playback.| audioPlayer.on('play', () => { // Set the 'play' event callback.
| reset()<sup>7+</sup> | Resets the audio source to be played.| console.info('audio play success');
| setVolume(vol:&nbsp;number) | Sets playback volume.| // The Play button is changed to the pausable state.
| seek(timeMs:&nbsp;number) | Changes the playback position.| });
| src:string | Defines the URI of an audio file to play.| audioPlayer.on('pause', () => { // Set the 'pause' event callback.
| state:AudioState | Defines the playback state.| console.info('audio pause success');
| currentTime:number | Defines the current playback position.| // The Play button is changed to the playable state.
| duration:number | Defines the playback duration. The value **-1** is returned if the data source does not support playback position change, for example, in the real-time streaming media scenario.| });
| loop:boolean | Defines whether to loop audio playback.| audioPlayer.on('stop', () => { // Set the 'stop' event callback.
| on('play',&nbsp;function&nbsp;callback) | Subscribes to the playback start event.| console.info('audio stop success');
| on('pause',&nbsp;function&nbsp;callback) | Subscribes to the playback pause event.| // The playback stops, the playback progress bar returns to 0, and the Play button is changed to the playable state.
| on('stop',&nbsp;function&nbsp;callback) | Subscribes to the playback stop event.| });
| on('reset',&nbsp;function&nbsp;callback) | Subscribes to the playback reset event.| audioPlayer.on('reset', () => { // Set the 'reset' event callback.
| on('finish',function&nbsp;callback) | Subscribes to the playback end event.| console.info('audio reset success');
| on('error',&nbsp;function&nbsp;callback) | Subscribes to the playback error event.| // You can reconfigure the src attribute to play another audio file.
| on('dataload',&nbsp;function&nbsp;callback) | Subscribes to the data loading event.| });
| on('volumeChange',&nbsp;function&nbsp;callback) | Subscribes to the volume change event.| audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback.
| on('timeUpdate',&nbsp;function&nbsp;callback) | Subscribes to the progress change event.| if (typeof(seekDoneTime) == 'undefined') {
console.info('audio seek fail');
1. Create an audio player.
```
import media from '@ohos.multimedia.media';
var player = media.createAudioPlayer();
```
2. Set the subscription events.
```
player.on('play', (err, action) => {
if (err) {
console.error('Error returned in the play() callback.');
return;
}
console.info('Current player duration: '+ player.duration);
console.info('Current player time: ' + player.currentTime);
console.info('Current player status: '+player.state);
console.info('Pause MP3');
player.pause();
});
player.on('pause', (err, action) => {
if (err) {
console.error('Error returned in the pause() callback.');
return; return;
}
console.info('Current player status: ' + player.state);
console.info('Current player time: ' + player.currentTime);
player.seek(30000); // Seek for 30 seconds.
});
player.on('stop', (err, action) => {
if (err) {
console.error('Error returned in the stop() callback.');
return;
}
console.info('stop callback invoked. State:' + player.state);
player.reset();
});
player.on('dataLoad', (err, action) => {
if (err) {
console.error('Error returned in the dataLoad() callback.');
return;
}
console.info('dataLoad callback invoked. Current time: ' + player.currentTime);
console.info('Duration of the source:' + player.duration);
player.play();
});
player.on('reset', (err, action) => {
if (err) {
console.error('Error returned in the reset() callback.');
return;
}
console.info('reset callback invoked.');
player.release();
});
player.on('finish', (err, action) => {
if (err) {
console.error('Error returned in the finish() callback.');
return;
} }
console.info('finish callback invoked.'); console.info('audio seek success, and seek time is ' + seekDoneTime);
}); // The playback progress bar is updated to the seek position.
player.on('timeUpdate', (seekTime, action) => { });
console.info('Seek time: ' + seekTime); audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
console.info('Current player time: ' + player.currentTime); console.info('audio volumeChange success');
var newTime = player.currentTime; // Display the updated volume.
if(newTime == 30000) { });
console.info('Seek succeeded. New time: ' + newTime); audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
} else { console.info('audio play finish');
console.error('Seek failed: ', + newTime); });
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}`);
});
}
function printfDescription(obj) {
for (let item in obj) {
let property = obj[item];
console.info('audio key is ' + item);
console.info('audio value is ' + property);
}
}
// 1. Create an audioPlayer instance.
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.
// 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]);
} }
player.stop(); } else {
}); console.log(`audio getTrackDescription fail, error:${error.message}`);
player.on('error', (err) => { }
console.error('Player error: ${err.message}'); });
}); // 8. Stop playback.
``` audioPlayer.stop(); // Trigger the 'stop' event callback.
// 9. Reset the playback resources.
3. Start playback. audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
``` // 10. Release the resource.
var audioSourceMp3 = 'file://test.mp3'; audioPlayer.release(); // Release the AudioPlayer resource.
player.src = audioSourceMp3; audioPlayer = undefined;
player.loop = true; ```
```
### Normal Playback Scenario
```js
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');
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
});
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
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.
```
### Switching to the Next Song
```js
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');
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
});
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
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.
/* 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';
```
### Looping a Song
```js
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');
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
});
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
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.
```
# Audio Playback and Recording # Media
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))
- Audio recording ([AudioRecorder](#audiorecorder))
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.
## Modules to Import ## Modules to Import
``` ```js
import media from '@ohos.multimedia.media'; import media from '@ohos.multimedia.media';
``` ```
## Required Permissions ## media.createAudioPlayer
None
## media.createAudioPlayer createAudioPlayer(): [AudioPlayer](#audioplayer)
Creates an **AudioPlayer** instance. Creates an **AudioPlayer** instance in synchronous mode.
**Return values** **Return values**
| Type | Description | | Type| Description|
| --------------------------- | ------------------------------------------------------------ | | --------------------------- | ------------------------------------------------------------ |
| [AudioPlayer](#audioplayer) | Returns the **AudioPlayer** instance if the operation is successful; returns **null** otherwise. | | [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();
```
## media.createAudioPlayerAsync<sup>8+</sup>
createAudioPlayerAsync(callback: AsyncCallback\<[AudioPlayer](#audioplayer)>): void
Creates an **AudioPlayer** instance in asynchronous mode. This method uses a callback to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | ------------------------------------------ | ---- | ------------------------------ |
| callback | AsyncCallback<[AudioPlayer](#audioplayer)> | Yes| Callback used to return the **AudioPlayer** instance created.|
**Example** **Example**
```js
media.createAudioPlayerAsync((error, audio) => {
if (typeof(audio) != 'undefined') {
audioPlayer = audio;
console.info('audio createAudioPlayerAsync success');
} else {
console.info(`audio createAudioPlayerAsync fail, error:${error.message}`);
}
});
``` ```
var audioplayer = media.createAudioPlayer();
## media.createAudioPlayerAsync<sup>8+</sup>
createAudioPlayerAsync: Promise<[AudioPlayer](#audioplayer)>
Creates an **AudioPlayer** instance in asynchronous mode. This method uses a promise to return the result.
**Return values**
| Type| Description|
| ------------------------------------ | ----------------------------------- |
| Promise<[AudioPlayer](#audioplayer)> | Promise used to return the **AudioPlayer** instance created.|
**Example**
```js
function failureCallback(error) {
console.info(`audio failureCallback, error:${error.message}`);
}
function catchCallback(error) {
console.info(`audio catchCallback, error:${error.message}`);
}
await media.createAudioPlayerAsync.then((audio) => {
if (typeof(audio) != 'undefined') {
audioPlayer = audio;
console.info('audio createAudioPlayerAsync success');
} else {
console.info('audio createAudioPlayerAsync fail');
}
}, failureCallback).catch(catchCallback);
``` ```
## media.createAudioRecorder ## media.createAudioRecorder
createAudioRecorder(): AudioRecorder createAudioRecorder(): AudioRecorder
Creates an **AudioRecorder** instance to control audio recording. Creates an **AudioRecorder** instance to control audio recording.
**Return values** **Return values**
| Type | Description | | Type| Description|
| ------------------------------- | ------------------------------------------------------------ | | ------------------------------- | ----------------------------------------- |
| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. | | [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise.|
**Example** **Example**
...@@ -44,255 +107,486 @@ Creates an **AudioRecorder** instance to control audio recording. ...@@ -44,255 +107,486 @@ Creates an **AudioRecorder** instance to control audio recording.
var audiorecorder = media.createAudioRecorder(); var audiorecorder = media.createAudioRecorder();
``` ```
## MediaErrorCode<sup>8+</sup>
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.|
## MediaType<sup>8+</sup>
Enumerates the media types.
| Name| Value| Description|
| ------------------- | ---- | ------------------ |
| MEDIA_TYPE_AUD | 0 | Media.|
| MEDIA_TYPE_VID | 1 | Video.|
| MEDIA_TYPE_SUBTITLE | 2 | Subtitle. (under development)|
## CodecMimeType<sup>8+</sup>
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.|
## MediaDescriptionKey<sup>8+</sup>
Enumerates the media description keys.
| 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.|
## BufferingInfoType<sup>8+</sup>
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.|
## AudioPlayer ## AudioPlayer
Manages and plays audio. Before calling a method of **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayer) to create an **AudioPlayer** instance. 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.
For details about the audio playback demo, see [Audio Playback Development](.../media/audio-playback.md).
### Attributes ### Attributes<a name=audioplayer_Attributes></a>
| Name | Type | Readable | Writable | Description | | Name| Type| Readable| Writable| Description|
| ----------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | | ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ |
| src | string | Yes | Yes | Audio media URI. Popular audio formats (mp4, aac, mp3, and ogg) are supported. The value can be a local absolute path starting with **file://**. | | src | string | Yes| Yes| Audio media URI. The mainstream audio formats (MP4, AAC, MP3, and OGG) are supported. <br>**Examples of supported URIs**:<br>1. Local absolute path: file:///data/data/ohos.xxx.xxx/files/test.mp4<br>![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)<br>2. HTTP network playback path (under development)<br>3. HLS network playback path (under development)<br>4. FD playback (under development)<br>**Precautions**: <br>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 playback. | | 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 playback position. | | currentTime | number | Yes| No| Current audio playback position.|
| duration | number | Yes | No | Audio duration. | | duration | number | Yes| No| Audio duration.|
| state | [AudioState](#audiostate) | Yes | No | Playback status. | | state | [AudioState](#audiostate) | Yes| No| Audio playback state.|
### play ### play<a name=audioplayer_play></a>
play\(\): void play(): void
Starts audio playback. 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.
**Example** **Example**
``` ```js
audioplayer.src = 'file:///data/media/sounds.mp4'; audioPlayer.on('play', () => { // Set the 'play' event callback.
audioplayer.on('play', () => { console.log('audio play success');
console.log('Playback starts.');
}); });
audioplayer.play(); audioPlayer.play();
``` ```
### pause ### pause<a name=audioplayer_pause></a>
pause\(\): void pause(): void
Pauses audio playback. Pauses audio playback.
**Example** **Example**
``` ```js
audioplayer.src = 'file:///data/media/sounds.mp4'; audioPlayer.on('pause', () => { // Set the 'pause' event callback.
audioplayer.on('pause', () => { console.log('audio pause success');
console.log('Playback paused.');
}); });
audioplayer.pause(); audioPlayer.pause();
``` ```
### stop<a name=audioplayer_stop></a>
### stop stop(): void
stop\(\): void
Stops audio playback. Stops audio playback.
**Example** **Example**
``` ```js
audioplayer.src = 'file:///data/media/sounds.mp4'; audioPlayer.on('stop', () => { // Set the 'stop' event callback.
audioplayer.on('stop',() => { console.log('audio stop success');
console.log('Playback stopped.');
}); });
audioplayer.stop(); audioPlayer.stop();
``` ```
### reset<sup>7+</sup><a name=audioplayer_reset></a>
reset(): void
### seek Switches the audio resource to be played.
seek\(timeMs: number\): void **Example**
```js
audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.log('audio reset success');
});
audioPlayer.reset();
```
### seek<a name=audioplayer_seek></a>
seek(timeMs: number): void
Seeks to the specified playback position. Seeks to the specified playback position.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| ------ | ------ | --------- | ----------------------------- | | ------ | ------ | ---- | ------------------------------ |
| timeMs | number | Yes | Playback position to seek to. | | timeMs | number | Yes| Position to seek to, in milliseconds.|
**Example** **Example**
``` ```js
audioplayer.src = 'file:///data/media/sounds.mp4'; audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback.
audioplayer.on('timeupdate', (action) => { if (typeof (seekDoneTime) == 'undefined') {
var newTime = audioplayer.currenTime; console.info('audio seek fail');
if(newTime >= 30000) { return;
console.info('Seek succeeded. New time: ' + newTime); }
} else { console.log('audio seek success. seekDoneTime: ' + seekDoneTime);
console.info('Seek failed.');
}
}); });
audioplayer.seek(30000); audioPlayer.seek(30000); // Seek to 30000 ms.
``` ```
### setVolume ### setVolume<a name=audioplayer_setvolume></a>
setVolume\(vol: number\): void setVolume(vol: number): void
Sets the volume. Sets the volume.
**Parameters** **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** **Example**
``` ```js
audioplayer.src = 'file:///data/media/sounds.mp4'; audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
audioplayer.on('volumeChange', () => { console.log('audio volumeChange success');
console.log('Playback volume changed.');
}); });
audioplayer.setVolume(1); audioPlayer.setVolume(1); // Set the volume to 100%.
``` ```
### reset<sup>7+</sup> ### release<a name=audioplayer_release></a>
reset\(\): void release(): void
Switches the audio resource to be played. Releases this **AudioPlayer** instance.
**Example** **Example**
``` ```js
audioplay.reset(); audioPlayer.release();
audioPlayer = undefined;
``` ```
### release ### getTrackDescription<sup>8+</sup><a name=audioplayer_gettrackdescription1></a>
getTrackDescription(callback: AsyncCallback<Array<[MediaDescription](#mediadescription8)>>): void
release\(\): void Obtains the audio track information. This method uses a callback to return the result.
Releases audio resources. **Parameters**
| Name| Type| Mandatory| Description|
| -------- | ------------------------------------------------------------ | ---- | -------------------------- |
| callback | AsyncCallback<Array<[MediaDescription](#mediadescription8)>> | Yes| Callback used to return the audio track information obtained.|
**Example** **Example**
```js
function printfDescription(obj) {
for (let item in obj) {
let property = obj[item];
console.info('audio key is ' + item);
console.info('audio value is ' + property);
}
}
audioPlayer.getTrackDescription((error, arrlist) => {
if (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
}
} else {
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
});
``` ```
audioplay.release();
### getTrackDescription<sup>8+</sup><a name=audioplayer_gettrackdescription2></a>
getTrackDescription(): Promise<Array<[MediaDescription](#mediadescription8)>>
Obtains the audio track information. This method uses a promise to return the result.
**Return values**
| Type| Description|
| ------------------------------------------------------ | ------------------------------- |
| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the audio track information obtained.|
**Example**
```js
function printfDescription(obj) {
for (let item in obj) {
let property = obj[item];
console.info('audio key is ' + item);
console.info('audio value is ' + property);
}
}
function failureCallback(error) {
console.info(`audio failureCallback, error:${error.message}`);
}
function catchCallback(error) {
console.info(`audio catchCallback, error:${error.message}`);
}
await audioPlayer.getTrackDescription.then((arrlist) => {
if (typeof (arrlist) != 'undefined') {
arrayDescription = arrlist;
} else {
console.log('audio getTrackDescription fail');
}
}, failureCallback).catch(catchCallback);
for (let i = 0; i < arrayDescription.length; i++) {
printfDescription(arrayDescription[i]);
}
``` ```
### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') ### on('bufferingUpdate')<sup>8+</sup>
Listens for audio playback events. on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void
on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void) Subscribes to the audio buffering update event.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | --------- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the playback event to listen for. The following events are supported: **play**, **pause**, **stop**, **reset**, **dataLoad**, **finish**, and **volumeChange**.<br>- The **play** event is triggered when audio playback starts. <br/>- The **pause** event is triggered when audio playback is paused.<br/>- The **stop** event is triggered when audio playback stops.<br/>- The **reset** event is triggered when the player is reset.<br/>- The **dataLoad** event is triggered when audio data is loaded.<br/>- The **finish** event is triggered when audio playback is finished.<br/>- The **volumeChange** event is triggered when the playback volume changes. | | type | string | Yes| Type of the event to subscribe to, which is 'bufferingUpdate' in this example.|
| callback | function | Yes | Callback used to listen for the playback event. | | callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | Yes| Callback invoked when the event is triggered. <br>When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.|
**Example** **Example**
```js
audioPlayer.on('bufferingUpdate', (infoType, value) => {
console.log('audio bufferingInfo type: ' + infoType);
console.log('audio bufferingInfo value: ' + value);
});
``` ```
audioplayer.src = 'file://xxx/sounds.mp4';
audioplayer.on('play', () => { ### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange')
console.log('Playback starts.');
on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void
Subscribes to the audio playback events.
**Parameters**
| 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' <br>- The 'play' event is triggered when the [play()](#audioplayer_play) method is called and audio playback starts. <br>- The 'pause' event is triggered when the [pause()](#audioplayer_pause) method is called and audio playback is paused. <br>- The 'stop' event is triggered when the [stop()](#audioplayer_stop) method is called and audio playback stops. <br>- The 'reset' event is triggered when the [reset()](#audioplayer_reset) method is called and audio playback is reset. <br>- The 'dataLoad' event is triggered when the audio data is loaded, that is, when the **src** attribute is configured. <br>- The 'finish' event is triggered when the audio playback is finished. <br>- The 'volumeChange' event is triggered when the [setVolume()](#audioplayer_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(); // 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(); // Start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
audioPlayer.seek(30000); // Call the seek() method and trigger the 'timeUpdate' event callback.
}); });
audioplayer.play(); audioPlayer.on('pause', () => { // Set the 'pause' event callback.
console.info('audio pause success');
audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback.
});
audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio reset success');
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
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); // Set the volume to 50% and trigger the 'volumeChange' event callback.
});
audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
console.info('audio volumeChange success');
audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback.
});
audioPlayer.on('finish', () => { // Set the 'finish' event callback.
console.info('audio play finish');
audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback.
});
audioPlayer.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, 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.
``` ```
### on('timeUpdate') ### on('timeUpdate')
on(type: 'timeUpdate', callback: Callback\<number>): void on(type: 'timeUpdate', callback: Callback\<number>): void
Listens for audio playback timestamp update events. Subscribes to the 'timeUpdate' event.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | ---------------------- | --------- | ------------------------------------------------------------ | | -------- | ----------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the playback event to listen for. Only the **timeUpdate** event is supported.<br>- The **timeUpdate** event is triggered when the audio playback timestamp is updated. It is also triggered when the **seek** method is called. | | type | string | Yes| Type of the event to subscribe to, which is 'timeUpdate' in this method. <br>The 'timeUpdate' event is triggered when the [seek()](#audioplayer_seek) method is called.|
| callback | Callback&lt;number&gt; | Yes | Callback used to listen for the playback event. | | callback | Callback\<number> | Yes| Callback invoked when the event is triggered. The input parameter of the callback is the time when the seek operation is successful.|
**Example** **Example**
``` ```js
audioplayer.src = 'file://xxx/sounds.mp4'; audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback.
audioplayer.on('timeupdate', (newTime ) => { if (typeof (seekDoneTime) == 'undefined') {
if(newTime >= 30000) { console.info('audio seek fail');
console.info('Seek succeeded. New time: ' + newTime); return;
} else { }
console.info('Seek failed.'); console.log('audio seek success. seekDoneTime: ' + seekDoneTime);
}
}); });
audioplayer.seek(30000); audioPlayer.seek(30000); // Seek to 30000 ms.
``` ```
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback): void on(type: 'error', callback: ErrorCallback): void
Listens for playback error events. Subscribes to the audio playback error event.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | ------------- | --------- | ------------------------------------------------------------ | | -------- | ------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the playback error event to listen for.<br>- The **error** event is triggered when an error occurs during audio playback. | | type | string | Yes| Type of the event to subscribe to, which is 'error' in this method. <br>The 'error' event is triggered when an error occurs during audio playback.|
| callback | ErrorCallback | Yes | Callback used to listen for the playback event. | | callback | ErrorCallback | Yes| Callback invoked when the event is triggered.|
**Example** **Example**
``` ```js
audioplayer.src = 'file:///data/sounds.mp4'; audioPlayer.on('error', (error) => { // Set the error event callback.
audioplayer.on('error', (err) => { console.info(`audio error called, errName is ${error.name}`); // Print the error name.
console.info('error callback info: ' + err); 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(30000); audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event.
``` ```
## AudioState ## AudioState
Describes the audio playback state. Describes the audio playback state. 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.|
| error<sup>8+</sup> | string | Audio playback is in the error state.|
| Name | Description | ## MediaDescription<sup>8+</sup>
| ------- | -------------------------- |
| idle | Audio playback is idle. | ### [key : string] : any
| playing | The audio is being played. |
| paused | Audio playback is paused. | Defines media information in key-value mode.
| stopped | Audio playback is stopped. |
| 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).|
**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 ## AudioRecorder
Provides methods to record audio. Before calling an **AudioRecorder** method, you must use [createAudioRecorder\(\)](#mediacreateaudiorecorder) to create an **AudioRecorder** instance. Implements audio recording. Before calling a method of the **AudioRecorder** class, you must call [createAudioRecorder()](#createaudiorecorder-audiorecorder) to create an **AudioRecorder** instance.
### prepare ### prepare
prepare(config: AudioRecorderConfig): void prepare(config: AudioRecorderConfig): void
Prepares for recording.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| ------ | ------------------------------------------- | --------- | ------------------------------------------------------------ | | ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ |
| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Recording parameters, including the audio output URI, encoding format, sampling rate, and number of audio channels | | config | [AudioRecorderConfig](#audiorecorderconfig) | Yes| Recording parameters, including the audio output URI, encoding format, sampling rate, and number of audio channels.|
**Example** **Example**
``` ```
let audioRecorderConfig = { let audioRecorderConfig = {
audioEncoder : AAC_LC , audioEncoder : AAC_LC ,
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
format : AAC_ADTS, format : AAC_ADTS,
uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a',
} }
audiorecorder.prepare(audioRecorderConfig) audiorecorder.prepare(audioRecorderConfig)
``` ```
### start ### start
start(): void start(): void
...@@ -321,6 +615,8 @@ audiorecorder.stop(); ...@@ -321,6 +615,8 @@ audiorecorder.stop();
release(): void release(): void
Releases this **AudioRecorder** instance.
**Example** **Example**
``` ```
...@@ -333,7 +629,7 @@ reset(): void ...@@ -333,7 +629,7 @@ reset(): void
Resets audio recording. Resets audio recording.
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. 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.
**Example** **Example**
...@@ -345,14 +641,14 @@ audiorecorder.reset(); ...@@ -345,14 +641,14 @@ audiorecorder.reset();
on(type: 'prepare' | 'start' | 'stop' | 'release' | 'reset', callback: () => void): void on(type: 'prepare' | 'start' | 'stop' | 'release' | 'reset', callback: () => void): void
Listens for audio recording events. Subscribes to the audio recording events.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | --------- | ------------------------------------------------------------ | | -------- | -------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the audio recording event to listen for. The following events are supported: **prepare**, **start**, **stop**, **release**, and **reset**.<br>- The **prepare** event is triggered when the audio recording preparation is complete.<br/>- The **start** event is triggered when audio recording starts.<br/>- The **stop** event is triggered when audio recording stops.<br/>- The **release** event is triggered when resources related to audio recording are released.<br/>- The **reset** event is triggered when audio recording is reset. | | type | string | Yes| Type of the event to subscribe to. The following events are supported: 'prepare'\|'start'\|'stop'\|'release'\|'reset' <br/>- The 'prepare' event is triggered when audio recording preparation is complete. <br/>- The 'start' event is triggered when audio recording starts. <br/>- The 'stop' event is triggered when audio recording is stopped. <br/>- The 'release' event is triggered when the resources related to audio recording are released. <br/>- The 'reset' event is triggered when audio recording is reset.|
| callback | function | Yes | Callback used to listen for the audio recording event. | | callback | function | Yes| Callback invoked when the event is triggered.|
**Example** **Example**
...@@ -367,41 +663,44 @@ audiorecorder.on('prepare', () => { ...@@ -367,41 +663,44 @@ audiorecorder.on('prepare', () => {
on(type: 'error', callback: ErrorCallback): void on(type: 'error', callback: ErrorCallback): void
Listens for audio recording error events. Subscribes to the audio recording error event.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | --------- | ------------------------------------------------------------ | | -------- | ------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the audio recording error event to listen for.<br>- The **error** event is triggered when an error occurs during audio recording. | | type | string | Yes| Type of the event to subscribe to, which is 'error' in this method. <br/>The 'error' event is triggered when an error occurs during audio recording.|
| callback | function | Yes | Callback used to listen for the audio recording event. | | callback | ErrorCallback | Yes| Callback invoked when the event is triggered.|
## AudioRecorderConfig ## AudioRecorderConfig
Describes audio recording configurations. Describes audio recording configurations.
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| ------------------ | --------------------------------------- | --------- | ------------------------------------------------------------ | | ------------------ | --------------------------------------- | ---- | ------------------------------------------------------------ |
| audioEncoder | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**. | | audioEncoder | [AudioEncoder](#audioencoder) | No| Audio encoding format. The default value is **AAC_LC**.|
| audioEncodeBitRate | number | No | Bit rate for audio encoding. The default value is **48000**. | | audioEncodeBitRate | number | No| Audio encoding bit rate. The default value is **48000**.|
| audioSampleRate | number | No | Audio sampling 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**. | | 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**. | | format | [AudioOutputFormat](#audiooutputformat) | No| Audio output format. The default value is **MPEG_4**.|
| uri | string | Yes | Audio output URI. The following types of URIs are supported:<br/>1. Absolute path:<br>file:///data/data/ohos.xxx.xxx/cache/test.mp4![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)<br/> 2. Path with the file descriptor (FD): file://1 (FD number) | | uri | string | Yes| Audio output URI. The following URI types are supported:<br/> 1. Absolute file path: file:///data/data/ohos.xxx.xxx/cache/test.mp4![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)<br/>2. FD path: file://1&nbsp;(fd&nbsp;number)|
## AudioEncoder ## AudioEncoder
Enumerates audio encoding formats. Enumerates the audio encoding formats.
| Name| Default Value| Description|
| ------ | ------ | ------------------------------------------------------------ |
| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).|
| Name | Default Value | Description |
| ------ | ------------- | ---------------------------------------------- |
| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC). |
## AudioOutputFormat ## AudioOutputFormat
Enumerates audio output formats. Enumerates the audio output formats.
| Name | Default Value | Description | | Name| Default Value| Description|
| -------- | ------------- | ------------------------------------------------------------ | | -------- | ------ | ------------------------------------------------------------ |
| MPEG_4 | 2 | MPEG-4. | | MPEG_4 | 2 | MPEG-4.|
| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), a transmission stream format of Advanced Audio Coding (AAC) audio. | | AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.|
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册