1# Using AVPlayer for Audio Playback 2 3The AVPlayer is used to play raw media assets in an end-to-end manner. In this topic, you will learn how to use the AVPlayer to play a complete piece of music. 4 5If you want the application to continue playing the music in the background or when the screen is off, you must use the [AVSession](avsession-overview.md) and [continuous task](../task-management/continuous-task-dev-guide.md) to prevent the playback from being forcibly interrupted by the system. 6 7 8The full playback process includes creating an **AVPlayer** instance, setting the media asset to play, setting playback parameters (volume, speed, and focus mode), controlling playback (play, pause, seek, and stop), resetting the playback configuration, and releasing the instance. 9 10 11During application development, you can use the **state** attribute of the AVPlayer to obtain the AVPlayer state or call **on('stateChange')** to listen for state changes. If the application performs an operation when the AVPlayer is not in the given state, the system may throw an exception or generate other undefined behavior. 12 13 14**Figure 1** Playback state transition 15![Playback state change](figures/playback-status-change.png) 16 17For details about the state, see [AVPlayerState](../reference/apis/js-apis-media.md#avplayerstate9). When the AVPlayer is in the **prepared**, **playing**, **paused**, or **completed** state, the playback engine is working and a large amount of RAM is occupied. If your application does not need to use the AVPlayer, call **reset()** or **release()** to release the instance. 18 19## How to Develop 20 21Read [AVPlayer](../reference/apis/js-apis-media.md#avplayer9) for the API reference. 22 231. Call **createAVPlayer()** to create an **AVPlayer** instance. The AVPlayer is the **idle** state. 24 252. Set the events to listen for, which will be used in the full-process scenario. The table below lists the supported events. 26 | Event Type| Description| 27 | -------- | -------- | 28 | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVPlayer.| 29 | error | Mandatory; used to listen for AVPlayer errors.| 30 | durationUpdate | Used to listen for progress bar updates to refresh the media asset duration.| 31 | timeUpdate | Used to listen for the current position of the progress bar to refresh the current time.| 32 | seekDone | Used to listen for the completion status of the **seek()** request.<br>This event is reported when the AVPlayer seeks to the playback position specified in **seek()**.| 33 | speedDone | Used to listen for the completion status of the **setSpeed()** request.<br>This event is reported when the AVPlayer plays music at the speed specified in **setSpeed()**.| 34 | volumeChange | Used to listen for the completion status of the **setVolume()** request.<br>This event is reported when the AVPlayer plays music at the volume specified in **setVolume()**.| 35 | bufferingUpdate | Used to listen for network playback buffer information. This event reports the buffer percentage and playback progress.| 36 | audioInterrupt | Used to listen for audio interruption. This event is used together with the **audioInterruptMode** attribute.<br>This event is reported when the current audio playback is interrupted by another (for example, when a call is coming), so the application can process the event in time.| 37 383. Set the media asset URL. The AVPlayer enters the **initialized** state. 39 > **NOTE** 40 > 41 > The URL in the code snippet below is for reference only. You need to check the media asset validity and set the URL based on service requirements. 42 > 43 > - If local files are used for playback, ensure that the files are available and the application sandbox path is used for access. For details about how to obtain the application sandbox path, see [Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path). For details about the application sandbox and how to push files to the application sandbox, see [File Management](../file-management/app-sandbox-directory.md). 44 > 45 > - If a network playback path is used, you must request the ohos.permission.INTERNET [permission](../security/accesstoken-guidelines.md). 46 > 47 > - You can also use **ResourceManager.getRawFd** to obtain the file descriptor of a file packed in the HAP file. For details, see [ResourceManager API Reference](../reference/apis/js-apis-resource-manager.md#getrawfd9). 48 > 49 > - The [playback formats and protocols](avplayer-avrecorder-overview.md#supported-formats-and-protocols) in use must be those supported by the system. 50 514. Call **prepare()** to switch the AVPlayer to the **prepared** state. In this state, you can obtain the duration of the media asset to play and set the volume. 52 535. Call **play()**, **pause()**, **seek()**, and **stop()** to perform audio playback control as required. 54 556. (Optional) Call **reset()** to reset the AVPlayer. The AVPlayer enters the **idle** state again and you can change the media asset URL. 56 577. Call **release()** to switch the AVPlayer to the **released** state. Now your application exits the playback. 58 59## Sample Code 60 61Refer to the sample code below to play a complete piece of music. 62 63```ts 64import media from '@ohos.multimedia.media'; 65import fs from '@ohos.file.fs'; 66import common from '@ohos.app.ability.common'; 67 68export class AVPlayerDemo { 69 private avPlayer; 70 private count: number = 0; 71 72 // Set AVPlayer callback functions. 73 setAVPlayerCallback() { 74 // Callback function for the seek operation. 75 this.avPlayer.on('seekDone', (seekDoneTime) => { 76 console.info(`AVPlayer seek succeeded, seek time is ${seekDoneTime}`); 77 }) 78 // Callback function for errors. If an error occurs during the operation on the AVPlayer, reset() is called to reset the AVPlayer. 79 this.avPlayer.on('error', (err) => { 80 console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`); 81 this.avPlayer.reset(); // Call reset() to reset the AVPlayer, which enters the idle state. 82 }) 83 // Callback function for state changes. 84 this.avPlayer.on('stateChange', async (state, reason) => { 85 switch (state) { 86 case 'idle': // This state is reported upon a successful callback of reset(). 87 console.info('AVPlayer state idle called.'); 88 this.avPlayer.release(); // Call release() to release the instance. 89 break; 90 case 'initialized': // This state is reported when the AVPlayer sets the playback source. 91 console.info('AVPlayerstate initialized called.'); 92 this.avPlayer.prepare().then(() => { 93 console.info('AVPlayer prepare succeeded.'); 94 }, (err) => { 95 console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`); 96 }); 97 break; 98 case 'prepared': // This state is reported upon a successful callback of prepare(). 99 console.info('AVPlayer state prepared called.'); 100 this.avPlayer.play(); // Call play() to start playback. 101 break; 102 case 'playing': // This state is reported upon a successful callback of play(). 103 console.info('AVPlayer state playing called.'); 104 if (this.count !== 0) { 105 console.info('AVPlayer start to seek.'); 106 this.avPlayer.seek (this.avPlayer.duration); // Call seek() to seek to the end of the audio clip. 107 } else { 108 this.avPlayer.pause(); // Call pause() to pause the playback. 109 } 110 this.count++; 111 break; 112 case 'paused': // This state is reported upon a successful callback of pause(). 113 console.info('AVPlayer state paused called.'); 114 this.avPlayer.play(); // Call play() again to start playback. 115 break; 116 case 'completed': // This state is reported upon the completion of the playback. 117 console.info('AVPlayer state completed called.'); 118 this.avPlayer.stop(); // Call stop() to stop the playback. 119 break; 120 case 'stopped': // This state is reported upon a successful callback of stop(). 121 console.info('AVPlayer state stopped called.'); 122 this.avPlayer.reset(); // Call reset() to reset the AVPlayer state. 123 break; 124 case 'released': 125 console.info('AVPlayer state released called.'); 126 break; 127 default: 128 console.info('AVPlayer state unknown called.'); 129 break; 130 } 131 }) 132 } 133 134 // The following demo shows how to use the file system to open the sandbox address, obtain the media file address, and play the media file using the URL attribute. 135 async avPlayerUrlDemo() { 136 // Create an AVPlayer instance. 137 this.avPlayer = await media.createAVPlayer(); 138 // Set a callback function for state changes. 139 this.setAVPlayerCallback(); 140 let fdPath = 'fd://'; 141 // Obtain the sandbox address filesDir through UIAbilityContext. The stage model is used as an example. 142 let context = getContext(this) as common.UIAbilityContext; 143 let pathDir = context.filesDir; 144 let path = pathDir + '/01.mp3'; 145 // Open the corresponding file address to obtain the file descriptor and assign a value to the URL to trigger the reporting of the initialized state. 146 let file = await fs.open(path); 147 fdPath = fdPath + '' + file.fd; 148 this.avPlayer.url = fdPath; 149 } 150 151 // The following demo shows how to use resourceManager to obtain the media file packed in the HAP file and play the media file by using the fdSrc attribute. 152 async avPlayerFdSrcDemo() { 153 // Create an AVPlayer instance. 154 this.avPlayer = await media.createAVPlayer(); 155 // Set a callback function for state changes. 156 this.setAVPlayerCallback(); 157 // Call getRawFd of the resourceManager member of UIAbilityContext to obtain the media asset URL. 158 // The return type is {fd,offset,length}, where fd indicates the file descriptor address of the HAP file, offset indicates the media asset offset, and length indicates the duration of the media asset to play. 159 let context = getContext(this) as common.UIAbilityContext; 160 let fileDescriptor = await context.resourceManager.getRawFd('01.mp3'); 161 // Assign a value to fdSrc to trigger the reporting of the initialized state. 162 this.avPlayer.fdSrc = fileDescriptor; 163 } 164} 165``` 166