1# Video Playback 2 3OpenHarmony provides two solutions for video playback development: 4 5- [AVPlayer](using-avplayer-for-playback.md) class: provides ArkTS and JS APIs to implement audio and video playback. It also supports parsing streaming media and local assets, decapsulating media assets, decoding video, and rendering video. It is applicable to end-to-end playback of media assets and can be used to play video files in MP4 and MKV formats. 6 7- <Video\> component: encapsulates basic video playback capabilities. It can be used to play video files after the data source and basic information are set. However, its scalability is poor. This component is provided by ArkUI. For details about how to use this component for video playback development, see [Video Component](../ui/arkts-common-components-video-player.md). 8 9In this topic, you will learn how to use the AVPlayer to develop a video playback service that plays a complete video file. If you want the application to continue playing the video 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. 10 11## Development Guidelines 12 13The full playback process includes creating an **AVPlayer** instance, setting the media asset to play and the window to display the video, setting playback parameters (volume, speed, and scale type), controlling playback (play, pause, seek, and stop), resetting the playback configuration, and releasing the instance. During 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 AudioPlayer is not in the given state, the system may throw an exception or generate other undefined behavior. 14 15**Figure 1** Playback state transition 16 17![Playback state change](figures/video-playback-status-change.png) 18 19For 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. 20 21### How to Develop 22 23Read [AVPlayer](../reference/apis/js-apis-media.md#avplayer9) for the API reference. 24 251. Call **createAVPlayer()** to create an **AVPlayer** instance. The AVPlayer is the **idle** state. 26 272. Set the events to listen for, which will be used in the full-process scenario. The table below lists the supported events. 28 | Event Type| Description| 29 | -------- | -------- | 30 | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVPlayer.| 31 | error | Mandatory; used to listen for AVPlayer errors.| 32 | durationUpdate | Used to listen for progress bar updates to refresh the media asset duration.| 33 | timeUpdate | Used to listen for the current position of the progress bar to refresh the current time.| 34 | 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()**.| 35 | speedDone | Used to listen for the completion status of the **setSpeed()** request.<br>This event is reported when the AVPlayer plays video at the speed specified in **setSpeed()**.| 36 | volumeChange | Used to listen for the completion status of the **setVolume()** request.<br>This event is reported when the AVPlayer plays video at the volume specified in **setVolume()**.| 37 | bitrateDone | Used to listen for the completion status of the **setBitrate()** request, which is used for HTTP Live Streaming (HLS) streams.<br>This event is reported when the AVPlayer plays video at the bit rate specified in **setBitrate()**.| 38 | availableBitrates | Used to listen for available bit rates of HLS resources. The available bit rates are provided for **setBitrate()**.| 39 | bufferingUpdate | Used to listen for network playback buffer information.| 40 | startRenderFrame | Used to listen for the rendering time of the first frame during video playback.| 41 | videoSizeChange | Used to listen for the width and height of video playback and adjust the window size and ratio.| 42 | 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.| 43 443. Set the media asset URL. The AVPlayer enters the **initialized** state. 45 > **NOTE** 46 > 47 > 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. 48 > 49 > - 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). 50 > 51 > - If a network playback path is used, you must request the ohos.permission.INTERNET [permission](../security/accesstoken-guidelines.md). 52 > 53 > - 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). 54 > 55 > - The [playback formats and protocols](avplayer-avrecorder-overview.md#supported-formats-and-protocols) in use must be those supported by the system. 56 574. Obtain and set the surface ID of the window to display the video. 58 The application obtains the surface ID from the XComponent. For details about the process, see [XComponent](../reference/arkui-ts/ts-basic-components-xcomponent.md). 59 605. 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 scale type and volume. 61 626. Call **play()**, **pause()**, **seek()**, and **stop()** to perform video playback control as required. 63 647. (Optional) Call **reset()** to reset the AVPlayer. The AVPlayer enters the **idle** state again and you can change the media asset URL. 65 668. Call **release()** to switch the AVPlayer to the **released** state. Now your application exits the playback. 67 68 69### Sample Code 70 71 72```ts 73import media from '@ohos.multimedia.media'; 74import fs from '@ohos.file.fs'; 75import common from '@ohos.app.ability.common'; 76 77export class AVPlayerDemo { 78 private avPlayer; 79 private count: number = 0; 80 private surfaceID: string; // The surfaceID parameter specifies the window used to display the video. Its value is obtained through the XComponent. 81 82 // Set AVPlayer callback functions. 83 setAVPlayerCallback() { 84 // Callback function for the seek operation. 85 this.avPlayer.on('seekDone', (seekDoneTime) => { 86 console.info(`AVPlayer seek succeeded, seek time is ${seekDoneTime}`); 87 }) 88 // Callback function for errors. If an error occurs during the operation on the AVPlayer, reset() is called to reset the AVPlayer. 89 this.avPlayer.on('error', (err) => { 90 console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`); 91 this.avPlayer.reset(); // Call reset() to reset the AVPlayer, which enters the idle state. 92 }) 93 // Callback function for state changes. 94 this.avPlayer.on('stateChange', async (state, reason) => { 95 switch (state) { 96 case 'idle': // This state is reported upon a successful callback of reset(). 97 console.info('AVPlayer state idle called.'); 98 this.avPlayer.release(); // Call release() to release the instance. 99 break; 100 case 'initialized': // This state is reported when the AVPlayer sets the playback source. 101 console.info('AVPlayerstate initialized called.'); 102 this.avPlayer.surfaceId = this.surfaceID // Set the window to display the video. This setting is not required when a pure audio asset is to be played. 103 this.avPlayer.prepare().then(() => { 104 console.info('AVPlayer prepare succeeded.'); 105 }, (err) => { 106 console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`); 107 }); 108 break; 109 case 'prepared': // This state is reported upon a successful callback of prepare(). 110 console.info('AVPlayer state prepared called.'); 111 this.avPlayer.play(); // Call play() to start playback. 112 break; 113 case 'playing': // This state is reported upon a successful callback of play(). 114 console.info('AVPlayer state playing called.'); 115 if (this.count !== 0) { 116 console.info('AVPlayer start to seek.'); 117 this.avPlayer.seek (this.avPlayer.duration); // Call seek() to seek to the end of the video clip. 118 } else { 119 this.avPlayer.pause(); // Call pause() to pause the playback. 120 } 121 this.count++; 122 break; 123 case 'paused': // This state is reported upon a successful callback of pause(). 124 console.info('AVPlayer state paused called.'); 125 this.avPlayer.play(); // Call play() again to start playback. 126 break; 127 case 'completed': // This state is reported upon the completion of the playback. 128 console.info('AVPlayer state completed called.'); 129 this.avPlayer.stop(); // Call stop() to stop the playback. 130 break; 131 case 'stopped': // This state is reported upon a successful callback of stop(). 132 console.info('AVPlayer state stopped called.'); 133 this.avPlayer.reset(); // Call reset() to reset the AVPlayer state. 134 break; 135 case 'released': 136 console.info('AVPlayer state released called.'); 137 break; 138 default: 139 console.info('AVPlayer state unknown called.'); 140 break; 141 } 142 }) 143 } 144 145 // 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. 146 async avPlayerUrlDemo() { 147 // Create an AVPlayer instance. 148 this.avPlayer = await media.createAVPlayer(); 149 // Set a callback function for state changes. 150 this.setAVPlayerCallback(); 151 let fdPath = 'fd://'; 152 let context = getContext(this) as common.UIAbilityContext; 153 // Obtain the sandbox address filesDir through UIAbilityContext. The stage model is used as an example. 154 let pathDir = context.filesDir; 155 let path = pathDir + '/H264_AAC.mp4'; 156 // 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. 157 let file = await fs.open(path); 158 fdPath = fdPath + '' + file.fd; 159 this.avPlayer.url = fdPath; 160 } 161 162 // 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. 163 async avPlayerFdSrcDemo() { 164 // Create an AVPlayer instance. 165 this.avPlayer = await media.createAVPlayer(); 166 // Set a callback function for state changes. 167 this.setAVPlayerCallback(); 168 // Call getRawFd of the resourceManager member of UIAbilityContext to obtain the media asset URL. 169 // 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. 170 let context = getContext(this) as common.UIAbilityContext; 171 let fileDescriptor = await context.resourceManager.getRawFd('H264_AAC.mp4'); 172 // Assign a value to fdSrc to trigger the reporting of the initialized state. 173 this.avPlayer.fdSrc = fileDescriptor; 174 } 175} 176``` 177