目录

Online Video Playback with AVPlayer

Overview

This guide is designed for developers working on online video playback apps. It addresses typical use cases in popular online video playback apps and demonstrates how to use the AVPlayer system media player to implement online video playback. This guide walks you through implementing the following scenarios:

Use AVPlayer to implement core video playback capabilities, including video resource loading, playing, pausing, stopping, and releasing. You can also use it to implement features such as playback speed adjustment, muted playback, window scaling mode setting, and volume adjustment. For details, see Basic Playback Controls with AVPlayer. For details about scenarios such as focus management, bullet comment sending and display, picture-in-picture (PiP), landscape/portrait mode switchover, and rotation perception, see Long-Form Video Playback with AVPlayer.

Online Video URL Setting

[h2]Scenario

When using AVPlayer to develop playback capabilities, you need to configure URLs based on the application scenario. It is key for streaming media online, whether it is live streams or local M3U8 files. The following streaming protocols are supported:

Streaming Media Protocol Typical Link Format
HLS https://xxxx/index.m3u8
DASH https://xxxx.mpd
HTTP/HTTPS https://xxxx.mp4
HTTP-FLV https://xxxx.flv

For details, see Using AVPlayer to Play Streaming Media (ArkTS)

This section demonstrates how to configure URLs for HLS and HTTP/HTTPS streams, as well as local M3U8 and MP4 files, so you can get your videos playing.

[h2]How to Implement

Set the video source of the AVPlayer using a URL in either of the following ways:

[h2]How to Develop

  1. Create an AVPlayer.

    public async initAVPlayer(source: VideoData, surfaceId: string) {
      // ...
      try {
        hilog.info(CommonConstants.LOG_DOMAIN, TAG, 'initPlayer videoPlay avPlayerDemo');
        this.avPlayer = await media.createAVPlayer();
        // ...
      } catch (err) {
        hilog.error(CommonConstants.LOG_DOMAIN, TAG,
          `initPlayer initPlayer, code is ${err.code}, message is ${err.message}`);
      }
    
    }
  2. Set the URL attribute of the AVPlayer, or call media.createMediaSourceWithUrl() to create a playback source based on the URL and configure the playback source to the AVPlayer. Then the AVPlayer automatically enters the initialized state.

    public async initAVPlayer(source: VideoData, surfaceId: string) {
      // ...
      try {
        hilog.info(CommonConstants.LOG_DOMAIN, TAG, 'initPlayer videoPlay avPlayerDemo');
        this.avPlayer = await media.createAVPlayer();
        this.setAVPlayerCallback();
        hilog.info(CommonConstants.LOG_DOMAIN, TAG, 'initPlayer videoPlay setAVPlayerCallback');
    
        if (!this.context) {
          hilog.error(CommonConstants.LOG_DOMAIN, TAG, `initPlayer failed context not set`);
          return
        }
        switch (this.curSource.type) {
          // ...
          case VideoDataType.URL:
            this.avPlayer.url = this.curSource.videoSrc;
            hilog.info(CommonConstants.LOG_DOMAIN, TAG,
              `initPlayer videoPlay url = ${JSON.stringify(this.avPlayer.url)}`);
            break;
          case VideoDataType.RAW_M3U8_FILE:
            let m3u8Fd = await this.context.resourceManager.getRawFd(this.curSource.videoSrc);
            let fdUrl = 'fd://' + m3u8Fd.fd + '?offset=' + m3u8Fd.offset + '&size=' + m3u8Fd.length;
            let mediaSource = media.createMediaSourceWithUrl(fdUrl);
            mediaSource.setMimeType(media.AVMimeTypes.APPLICATION_M3U8);
            let playbackStrategy: media.PlaybackStrategy = { preferredBufferDuration: 20, showFirstFrameOnPrepare: true };
            await this.avPlayer.setMediaSource(mediaSource, playbackStrategy);
            hilog.info(CommonConstants.LOG_DOMAIN, TAG, `initPlayer videoPlay fdUrl = ${JSON.stringify(fdUrl)}`);
            break;
          case VideoDataType.RAW_MP4_FILE:
            let mp4Fd = await this.context.resourceManager.getRawFd(this.curSource.videoSrc);
            let mp4FdUrl = 'fd://' + mp4Fd.fd;
            this.avPlayer.url = mp4FdUrl;
            hilog.info(CommonConstants.LOG_DOMAIN, TAG, `initPlayer videoPlay fdUrl = ${JSON.stringify(mp4FdUrl)}`);
            break;
    
          default:
            hilog.error(CommonConstants.LOG_DOMAIN, TAG, `initPlayer failed VideoDataType is invalid`);
            break;
        }
        await this.setCaption();
      } catch (err) {
        hilog.error(CommonConstants.LOG_DOMAIN, TAG,
          `initPlayer initPlayer, code is ${err.code}, message is ${err.message}`);
      }
    
    }

Online Video Buffering Bar

[h2]Scenario

Enable users to see how much of an online video has been buffered and is ready to play.

[h2]How to Implement

In this example, AVPlayer is used to implement online video playback, and Slider is used to implement video playback and display the buffering bar. Since the Slider component does not support multiple progress bars, the Stack layout is used to overlap the buffering slider and the progress slider to display both the buffering progress and the playback progress.

The value of the buffering slider is bound to the state variable currentBufferTime decorated with @State. By registering bufferingUpdate, you can obtain the estimated playback duration of the buffered content and calculate the current buffering progress based on the playback duration.

In the bufferingUpdate callback, when infoType is media.BufferingInfoType.CACHED_DURATION, value represents the estimated playable duration of buffered content. Since this is an estimate, the buffering progress may not be 100% accurate. For details about the callback function parameters of the bufferingUpdate event, see OnBufferingUpdateHandler.

[h2]How to Develop

  1. Create an AVPlayer and configure the playback source.

    public async initAVPlayer(source: VideoData, surfaceId: string) {
      // ...
      try {
        hilog.info(CommonConstants.LOG_DOMAIN, TAG, 'initPlayer videoPlay avPlayerDemo');
        this.avPlayer = await media.createAVPlayer();
        this.setAVPlayerCallback();
        hilog.info(CommonConstants.LOG_DOMAIN, TAG, 'initPlayer videoPlay setAVPlayerCallback');
    
        if (!this.context) {
          hilog.error(CommonConstants.LOG_DOMAIN, TAG, `initPlayer failed context not set`);
          return
        }
        switch (this.curSource.type) {
          // ...
          case VideoDataType.URL:
            this.avPlayer.url = this.curSource.videoSrc;
            hilog.info(CommonConstants.LOG_DOMAIN, TAG,
              `initPlayer videoPlay url = ${JSON.stringify(this.avPlayer.url)}`);
            break;
          // ...
        }
        await this.setCaption();
      } catch (err) {
        hilog.error(CommonConstants.LOG_DOMAIN, TAG,
          `initPlayer initPlayer, code is ${err.code}, message is ${err.message}`);
      }
    
    }
  2. Register timeUpdate and update the state variable currentTime decorated with @State in the function.

    private setAVPlayerCallback() {
      // ...
      this.avPlayer.on('timeUpdate', (time: number) => {
        this.currentTime = time;
        AppStorage.setOrCreate('CurrentTime', time);
        hilog.info(CommonConstants.LOG_DOMAIN, TAG,
          `setAVPlayerCallback timeUpdate success,and new time is = ${this.currentTime}`);
      });
      // ...
    }
  3. Register bufferingUpdate and update the state variable currentBufferTime decorated with @State in the function.

    private setAVPlayerCallback() {
      // ...
      this.avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
        hilog.info(CommonConstants.LOG_DOMAIN, TAG,
          `BufferedProgressBar bufferingUpdate, infoType is ${infoType}, value is ${value}.`);
        // ...
        if (infoType === media.BufferingInfoType.CACHED_DURATION && this.avPlayer) {
          this.currentBufferTime = Math.max(this.currentBufferTime, this.currentTime + value);
          hilog.info(CommonConstants.LOG_DOMAIN, TAG, `currentBufferTime: ${this.currentBufferTime}`)
        }
      });
    
      // ...
    }
  4. Bind currentTime to the value attribute of the playback slider, and bind currentBufferTime to the value attribute of the buffer slider. Use the Stack layout to overlap the playback slider and the buffer slider. Then, set trackColor of the playback slider to transparent, and set the style attribute of the buffer slider to SliderStyle.NONE to hide the slider.

    @Builder
    progressBuilder() {
      Stack() {
        Slider({
          value: this.avPlayerController.currentTime,
          min: CommonConstants.SLIDER_PROGRESS_MIN,
          max: this.avPlayerController.durationTime,
          step: CommonConstants.SLIDER_PROGRESS_STEP,
          direction: Axis.Horizontal
        })
          .blockColor(Color.White)
          .trackColor($r('app.color.track_color_show'))
          .selectedColor($r('app.color.slider_selected'))
          .trackThickness(5)
          .zIndex(1)
          .onChange((value: number) => {
            this.avPlayerController.videoSeek(value);
          })
    
        Slider({
          value: this.avPlayerController.currentBufferTime,
          min: CommonConstants.SLIDER_PROGRESS_MIN,
          max: this.avPlayerController.durationTime,
          step: CommonConstants.SLIDER_PROGRESS_STEP,
          direction: Axis.Horizontal,
          style: SliderStyle.NONE
        })
          .trackColor(Color.Grey)
          .selectedColor(Color.White)
          .blockColor($r('app.color.track_color_show'))
          .trackThickness(5)
          .margin({ left: 12, right: 12 })
          .zIndex(0)
      }
      .layoutWeight(1)
    }

Online Video Streaming Playback

[h2]Scenario

Network video streaming playback is a typical scenario in multimedia apps. Users do not need to wait for complete video resource loading (buffering) before playback can start. Instead, playback can begin once a sufficient amount of data has been buffered. The AVPlayer inherently supports streaming playback, and this section explains how to configure its buffer-related parameters.

[h2]AVPlayer Buffer Mechanism

For the buffer, the download thread is the producer, and the read thread is the consumer. The producer writes data into the buffer, and the consumer reads data from it.

Below we introduce several key waterline concepts in the buffer system. The four waterlines have the following values. The playback start waterline and download pause waterline (buffer size) can be controlled by configuring the AVPlayer's playback strategy, whereas the other two currently do not have configuration interfaces.

Watermark Default Value Description
Playback start watermark

If the download rate is greater than or equal to the bitrate, the playback start watermark is calculated as 0.3 seconds multiplied by the bitrate.

If the download rate is less than the bitrate, the playback start watermark is calculated as 5 seconds multiplied by the bitrate.

If the playback start watermark is less than 10 KB, the value 10 KB is used.

A balanced approach is taken between achieving quick startup and maintaining smooth playback.
Playback stop watermark Amount of data read at a time. If it is less than 5 KB, the value 5 KB is used. It prevents the available data in the buffer from being used up.
Download start watermark 480 KB It reduces thread launch frequency, focusing on batch downloading to minimize CPU and instruction count consumption.
Download pause watermark Buffer size It pauses download when the buffer is full. Modification is supported.

The default value of the playback start watermark is determined by download speed. If the download speed matches or beats the bitrate, the video starts to play after being buffered for 0.3 second (0.3 seconds times the bitrate). If the download speed lags behind the bitrate, the video starts to play after being buffered for 5 seconds (5 seconds times the bitrate). This enables fast starts in good network conditions and prevents frequent play/pause switching in poor network conditions. If the default settings are not met, you can configure PlaybackStrategy to control the playback start watermark.

The download pause waterline represents the maximum space occupied by buffered, unplayed data. It depends on buffer size and can be adjusted indirectly by configuring the buffer size. Setting it too low can lead to playback interruptions on an unstable connection. Conversely, setting it too high could unnecessarily consume extra bandwidth. The default value is 20 MB, which is the maximum. You can set the preferredBufferDuration parameter in PlaybackStrategy to control the buffer size as needed. The unit of preferredBufferDuration is second, and the buffer size is equal to the value of preferredBufferDuration multiplied by 1 MB. For example, if preferredBufferDuration is set to 20 seconds, the buffer size is 20 MB.

Default Buffer Size Custom Buffer Size
20 MB 5 MB to 20 MB

The playback start waterline and download pause waterline (buffer size) are controlled by the playback strategy of the AVPlayer. There are two ways to configure the playback strategy:

[h2]Using setMediaSource()

  1. Create an AVPlayer and call media.createMediaSourceWithUrl() to generate a MediaSource instance.

    public async initAVPlayer(source: VideoData, surfaceId: string) {
      // ...
      try {
        hilog.info(CommonConstants.LOG_DOMAIN, TAG, 'initPlayer videoPlay avPlayerDemo');
        this.avPlayer = await media.createAVPlayer();
        this.setAVPlayerCallback();
        hilog.info(CommonConstants.LOG_DOMAIN, TAG, 'initPlayer videoPlay setAVPlayerCallback');
    
        if (!this.context) {
          hilog.error(CommonConstants.LOG_DOMAIN, TAG, `initPlayer failed context not set`);
          return
        }
        switch (this.curSource.type) {
          // ...
          case VideoDataType.URL:
            this.avPlayer.url = this.curSource.videoSrc;
            hilog.info(CommonConstants.LOG_DOMAIN, TAG,
              `initPlayer videoPlay url = ${JSON.stringify(this.avPlayer.url)}`);
            break;
          // ...
        }
        await this.setCaption();
      } catch (err) {
        hilog.error(CommonConstants.LOG_DOMAIN, TAG,
          `initPlayer initPlayer, code is ${err.code}, message is ${err.message}`);
      }
    
    }
  2. Create a PlaybackStrategy instance and call setMediaSource() of AVPlayer to configure the PlaybackStrategy instance to AVPlayer.

    public async initAVPlayer(source: VideoData, surfaceId: string) {
      // ...
      try {
        // ...
        switch (this.curSource.type) {
          // ...
          case VideoDataType.RAW_M3U8_FILE:
            let m3u8Fd = await this.context.resourceManager.getRawFd(this.curSource.videoSrc);
            let fdUrl = 'fd://' + m3u8Fd.fd + '?offset=' + m3u8Fd.offset + '&size=' + m3u8Fd.length;
            let mediaSource = media.createMediaSourceWithUrl(fdUrl);
            mediaSource.setMimeType(media.AVMimeTypes.APPLICATION_M3U8);
            let playbackStrategy: media.PlaybackStrategy = { preferredBufferDuration: 20, showFirstFrameOnPrepare: true };
            await this.avPlayer.setMediaSource(mediaSource, playbackStrategy);
            hilog.info(CommonConstants.LOG_DOMAIN, TAG, `initPlayer videoPlay fdUrl = ${JSON.stringify(fdUrl)}`);
            break;
          // ...
        }
        await this.setCaption();
      } catch (err) {
        hilog.error(CommonConstants.LOG_DOMAIN, TAG,
          `initPlayer initPlayer, code is ${err.code}, message is ${err.message}`);
      }
    
    }

[h2]Using setPlaybackStrategy()

  1. Create an AVPlayer and initialize it by assigning a value to the AVPlayer.url property.

    public async initAVPlayer(source: VideoData, surfaceId: string) {
      // ...
      try {
        hilog.info(CommonConstants.LOG_DOMAIN, TAG, 'initPlayer videoPlay avPlayerDemo');
        this.avPlayer = await media.createAVPlayer();
        this.setAVPlayerCallback();
        hilog.info(CommonConstants.LOG_DOMAIN, TAG, 'initPlayer videoPlay setAVPlayerCallback');
    
        if (!this.context) {
          hilog.error(CommonConstants.LOG_DOMAIN, TAG, `initPlayer failed context not set`);
          return
        }
        switch (this.curSource.type) {
          // ...
          case VideoDataType.URL:
            this.avPlayer.url = this.curSource.videoSrc;
            hilog.info(CommonConstants.LOG_DOMAIN, TAG,
              `initPlayer videoPlay url = ${JSON.stringify(this.avPlayer.url)}`);
            break;
          // ...
        }
        await this.setCaption();
      } catch (err) {
        hilog.error(CommonConstants.LOG_DOMAIN, TAG,
          `initPlayer initPlayer, code is ${err.code}, message is ${err.message}`);
      }
    
    }
  2. Register the AVPlayer state callback, and configure the PlaybackStrategy instance in the initialized state callback.

    this.avPlayer.on('stateChange', async (state) => {
      if (!this.avPlayer) {
        return;
      }
      switch (state) {
        // ...
        case 'initialized':
          hilog.info(CommonConstants.LOG_DOMAIN, TAG, 'setAVPlayerCallback AVPlayerState initialized called.');
          this.avPlayer.surfaceId = this.surfaceID;
          hilog.info(CommonConstants.LOG_DOMAIN, TAG,
            `setAVPlayerCallback this.avPlayer.surfaceId = ${this.avPlayer.surfaceId}`);
          await this.avPlayer.setPlaybackStrategy({
            preferredBufferDurationForPlaying: 0.3,
            preferredBufferDuration: 20,
            showFirstFrameOnPrepare: true
          });
          this.avPlayer.prepare();
          break;
        // ...
      }
    });

Sample Code