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|
functionSetCallBack(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.|
// The Play button is changed to the pausable state.
| seek(timeMs: 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', function callback) | Subscribes to the playback start event.|
console.info('audio stop success');
| on('pause', function 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', function callback) | Subscribes to the playback stop event.|
});
| on('reset', function callback) | Subscribes to the playback reset event.|
audioPlayer.on('reset',()=>{// Set the 'reset' event callback.
| on('finish',function callback) | Subscribes to the playback end event.|
console.info('audio reset success');
| on('error', function callback) | Subscribes to the playback error event.|
// You can reconfigure the src attribute to play another audio file.
| on('dataload', function callback) | Subscribes to the data loading event.|
});
| on('volumeChange', function callback) | Subscribes to the volume change event.|
audioPlayer.on('timeUpdate',(seekDoneTime)=>{// Set the 'timeUpdate' event callback.
| on('timeUpdate', function 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.');
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
importmediafrom'@ohos.multimedia.media';
importmediafrom'@ohos.multimedia.media';
```
```
## Required Permissions
## media.createAudioPlayer
None
## media.createAudioPlayer
createAudioPlayer(): [AudioPlayer](#audioplayer)
Creates an **AudioPlayer** instance.
Creates an **AudioPlayer** instance in synchronous mode.
| [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.|
| 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 |
| 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><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.
| 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**.|
| 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
letaudioPlayer=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.
| 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<number> | 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);
| 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.|
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.
| 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.
| 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.|
| 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.|
| 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<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<br/>2. FD path: file://1 (fd number)|