目录

Long-Form Video Playback with AVPlayer

Overview

This guide is designed for developers working on video playback applications. It addresses typical use cases in popular video playback applications and demonstrates how to use AVPlayer, the system's media player, to implement long-form video playback. This document provides guidance for you to implement development scenarios such as brightness control, focus management, foreground/background perception, bullet comment sending and display, video screenshot, picture-in-picture (PiP) playback, background playback and access to the Media Controller, and first-frame display of videos.

For details about the basic playback control, precise seeking, muted playback, window zoom setting, playback speed adjustment, volume control, and subtitle mounting scenarios, see Basic Playback Controls with AVPlayer.

This course describes the following:

Brightness Control

[h2]Scenario

Enable users to adjust the screen brightness with a swipe gesture while they watch videos in landscape mode.

[h2]How to Implement

Use the Slider component to set the brightness panel and bind the PanGesture event to the component. When the pan gesture is moving, call setWindowBrightness() to increase or decrease brightness when swiping up or down, respectively.

[h2]How to Develop

  1. In full-screen mode, place a Slider component on the right to display the brightness level.

    Column() {
      Stack() {
        Slider({
          value: this.screenBrightness,
          min: 0,
          max: 1,
          step: 0.05,
          style: SliderStyle.NONE,
          direction: Axis.Vertical,
          reverse: true
        })
          .visibility(this.visible ? Visibility.Visible : Visibility.Hidden)
          .height(160)
          .selectedColor(Color.White)
          .trackColor(Color.Black)
          .trackThickness(40)
          .onChange(async (value: number) => {
            this.screenBrightness = value;
            let windowStage: window.WindowStage = AppStorage.get(KeyConstants.KEY_WINDOW_STAGE) as window.WindowStage;
            try {
              let mainWin: window.Window = windowStage.getMainWindowSync();
              await mainWin.setWindowBrightness(value);
            } catch (exception) {
              Logger.error(TAG, `getMainWindowSync failed: code: ${exception.code}, message: ${exception.message}`);
            }
          })
    
        Image($r('app.media.sun_max_fill'))
          .visibility(this.visible ? Visibility.Visible : Visibility.Hidden)
          .margin({ top: 120 })
          .width(20)
          .height(20)
      }
      .margin({
        top: 0,
        right: 0
      })
    }
    .width('50%')
    .alignItems(HorizontalAlign.End)
    .justifyContent(FlexAlign.Center)
    .padding({
      right: 30,
      bottom: 20
    })
  2. Bind a PanGesture event on the video playback screen. Set the event to be triggered only when a vertical pan gesture is detected within the right-side area of the screen. Upon triggering, it invokes the setWindowBrightness() API to adjust the brightness. Here, setScreenBrightness() is a wrapper of setWindowBrightness().

    private processGesture(event: GestureEvent) {
      if (event.fingerList.length === 0) {
        return;
      }
      if (event.fingerList[0].globalX > (this.getUIContext().px2vp(this.screenWidth / 2))) {
        if (this.isInputtingBulletComment) {
          return;
        }
        this.visible = true;
        let curBrightness = this.screenBrightness - this.getUIContext().vp2px(event.offsetY) / this.screenHeight;
        curBrightness = this.getValidValue(curBrightness, 0.0, 1.0);
        this.screenBrightness = curBrightness;
        this.setScreenBrightness(this.screenBrightness);
      } else {
        this.visible = false;
        let curVolume = this.volume - this.getUIContext().vp2px(event.offsetY) / this.screenHeight;
        curVolume = this.getValidValue(curVolume, 0.0, 15.0);
        this.volume = curVolume;
      }
    }
    .gesture(
      PanGesture({ direction: PanDirection.Vertical })
        .onActionStart(() => {
        })
        .onActionUpdate((event: GestureEvent) => {
          this.processGesture(event);
        })
        .onActionEnd(() => {
          setTimeout(() => {
            this.visible = false;
          }, 3000)
        })
    )

Focus Management

[h2]Scenario

Manage audio focus during playback by correctly setting the audio stream type, managing interruption events, and customizing focus strategies.

[h2]How to Implement

Use the on('audioInterrupt') method of AVPlayer to listen for audio focus changes and perform corresponding processing based on the interruption type and interruption hint. For more information about focus management, see Audio Focus Management.

[h2]How to Develop

  1. Register on('audioInterrupt') through the AVPlayer instance to listen for external interruption events. When the interruption type is INTERRUPT_FORCE, the video playback is automatically interrupted.

  2. When the interruption type is INTERRUPT_SHARE and the hint is INTERRUPT_HINT_RESUME, call the videoPlay() API to resume video playback. Here, videoPlay() is a wrapper of play().

    private setInterruptCallback() {
      if (!this.avPlayer) {
        return;
      }
      this.avPlayer.on('audioInterrupt', async (interruptEvent: audio.InterruptEvent) => {
        if (interruptEvent.forceType === audio.InterruptForceType.INTERRUPT_FORCE) {
          switch (interruptEvent.hintType) {
            case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
            case audio.InterruptHint.INTERRUPT_HINT_STOP:
              this.isPlaying = false;
              this.updateIsPlay();
              break;
            case audio.InterruptHint.INTERRUPT_HINT_DUCK:
            case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
              break;
            default:
              break;
          }
        } else if (interruptEvent.forceType === audio.InterruptForceType.INTERRUPT_SHARE) {
          switch (interruptEvent.hintType) {
            case audio.InterruptHint.INTERRUPT_HINT_RESUME:
              this.videoPlay();
              break;
            default:
              break;
          }
        }
      });
    }

Foreground/Background State Detection

[h2]Scenario

Enable the video to resume playback from the original position when an application moves from the foreground to the background and then returns to the foreground.

[h2]How to Implement

Call the play() method of AVPlayer in the onPageShow() lifecycle method when the application is switched to the foreground, and call the pause() method of AVPlayer in the onPageHide() lifecycle method when the application is switched to the background.

[h2]How to Develop

  1. Change the status variable in onPageShow() and onPageHide() of the main page.

    onPageHide(): void {
      this.isPageShow = false;
    }
    onPageShow(): void {
      this.isPageShow = true;
    }
  2. Add the @Watch decorator to the state variable in the video playback component.

    @Prop @Watch('onPageShowChange') isPageShow: boolean = false;
  3. Listen for the onPageShowChange event and call the play/pause API of AVPlayer to pause the video when the application moves to the background and resume the video when it returns to the foreground. Here, avPlayerController is a controller instance that implements basic playback control based on the AVPlayer. resumePlayback() and pausePlay() are wrappers of play() and pause(), respectively.

    onPageShowChange() {
      if (!this.isPIPShow && this.curIndex === this.index) {
        this.isPageShow ? this.resumePlayback() : this.pausePlay();
      }
    }
    private resumePlayback() {
      if (!this.avPlayerController.isPlaying) {
        this.avPlayerController.videoPlay();
      }
    }
    private pausePlay() {
      if (this.avPlayerController.isPlaying) {
        this.avPlayerController.videoPause();
      }
    }

Bullet Comment Sending and Display

[h2]Scenario

Allow users to send real-time, on-screen comments during video playback or live streams, significantly enhancing user engagement and interactivity.

[h2]How to Implement

Use an array to store and send bullet comments, and implement the horizontal movement animation of bullet comments based on the setInterval() function and translate attribute.

[h2]How to Develop

  1. Define an empty array within the video playback component to store all active bullet comments. When a user submits a new comment, add the input content to this array.

    private sendBulletComment() {
      if (this.bulletCommentInput.trim()) {
        this.bulletComments = [...this.bulletComments, new BulletComment(this.bulletCommentInput, true)];
        this.bulletCommentInput = '';
        if (this.bulletComments.length > 50) {
          this.bulletComments = this.bulletComments.slice(1);
        }
      }
      this.resumePlayback();
    }
  2. In the bullet comment display component, call setInterval to set a timer. The timer periodically updates the translate attribute of the Text component that carries the bullet comment content to update the positions of all bullet comments.

    private startAnimation() {
      if (this.timerId > 0) {
        clearInterval(this.timerId);
      }
      this.timerId = setInterval(() => {
        let needUpdate = false;
        this.bulletComments.forEach(item => {
          const positionX = item.translateX - item.speed;
          if (positionX !== item.translateX) {
            item.translateX = positionX;
            needUpdate = true;
          }
        });
        const beforeLength = this.bulletComments.length;
        this.bulletComments =
          this.bulletComments.filter(item => item.translateX > -20);
        if (needUpdate || this.bulletComments.length !== beforeLength) {
          this.forceUpdate = !this.forceUpdate;
        }
      }, 16);
    }

Video Frame Capture

[h2]Scenario

Enable users to capture frames during video playback and perform fine-tuning by navigating to adjacent frames, ensuring the captured image meets their expectations.

[h2]How to Implement

Use XComponent as the media stream playback component and obtain the screenshot capability of the component through the ComponentSnapshot object.

[h2]How to Develop

  1. Call getUIContext().getComponentSnapshot().get() on the XComponent to capture a screenshot of the current frame.

    private async screenshot() {
      try {
        this.pixmap = await this.getUIContext().getComponentSnapshot().get(`videoXComponent_${this.curSource.index}`);
      } catch (exception) {
        Logger.error(TAG, `screenshot failed: code: ${exception.code}, message: ${exception.message}`);
      }
    }
  2. Call seek() of AVPlayer to seek to the previous or next second of the video timeline. Repeat step 1 to capture a new screenshot from the current position. Note: avPlayerController is the controller instance implemented based on the AVPlayer for basic playback controls, and videoSeek() is a wrapper of seek().

    private async clickPreviousFrame() {
      this.avPlayerController?.videoSeek(this.screenshotTime - 1000 / ScreenShotConstants.FRAME_RATE);
      this.pausePlay();
      if (this.previousFrameTimerId) {
        clearTimeout(this.previousFrameTimerId);
      }
      this.previousFrameTimerId = setTimeout(() => {
        this.screenshot()
      }, 500)
      this.screenshotTime -= 1000 / ScreenShotConstants.FRAME_RATE;
      this.screenshotTime = Math.max(0, Math.min(this.screenshotTime, this.avPlayerController.durationTime));
    }
    private async clickNextFrame() {
      this.avPlayerController?.videoSeek(this.screenshotTime + 1000 / ScreenShotConstants.FRAME_RATE);
      this.pausePlay();
      if (this.nextFrameTimerId) {
        clearTimeout(this.nextFrameTimerId);
      }
      this.nextFrameTimerId = setTimeout(() => {
        this.screenshot()
      }, 500)
      this.screenshotTime += 1000 / ScreenShotConstants.FRAME_RATE;
      this.screenshotTime = Math.max(0, Math.min(this.screenshotTime, this.avPlayerController.durationTime));
    }

PiP Playback

[h2]Scenario

Allow users to display the video content in a small, floating window, while they can perform other operations on the screen, enhancing their overall experience.

[h2]How to Implement

Use XComponent as the media stream playback component and implement basic PiP functions through the PiPWindow module.

  • Only the UI that uses the XComponent as the media stream playback component can enter PiP mode. The type of the XComponent must be set to surface or XComponentType.SURFACE.
  • In versions earlier than API version 20, PiP functionality using the XComponent is supported on phones and tablets. Starting from API version 20, support extends to phones, PCs/2-in-1 devices, and tablets.

[h2]How to Develop

  1. Create a PiP controller, and call setAutoStartEnabled()(true). This enables the automatic activation of PiP mode when the application is switched to the home screen.

    async createPipController() {
      if (!this.pipController) {
        try {
          this.pipController = await PiPWindow.create({
            context: this.context,
            componentController: this.xComponentController,
            templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY
          });
        } catch (exception) {
          Logger.error(TAG,
            `pipController init failed, Code:${exception.code}, message:${exception.message}`);
        }
      }
      this.pipController?.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
        this.onStateChange(state, reason);
      });
    
      this.pipController?.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
        this.onActionEvent(event, status);
      });
      this.pipController?.setAutoStartEnabled(true);
    }
  2. Register callbacks for the lifecycle and control events.

    onStateChange(state: PiPWindow.PiPState, reason: string) {
      switch (state) {
        case PiPWindow.PiPState.ABOUT_TO_START:
          this.curState = 'ABOUT_TO_START';
          break;
        case PiPWindow.PiPState.STARTED:
          this.curState = 'STARTED';
          let status: PiPWindow.PiPControlStatus =
            this.avPlayerController?.isPlaying ? PiPWindow.PiPControlStatus.PLAY : PiPWindow.PiPControlStatus.PAUSE;
          this.pipController?.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE, status);
          break;
        case PiPWindow.PiPState.ABOUT_TO_STOP:
          this.curState = 'ABOUT_TO_STOP';
          break;
        case PiPWindow.PiPState.STOPPED:
          this.curState = 'STOPPED';
          break;
        case PiPWindow.PiPState.ABOUT_TO_RESTORE:
          this.curState = 'ABOUT_TO_RESTORE';
          break;
        case PiPWindow.PiPState.ERROR:
          this.curState = 'ERROR';
          break;
        default:
          break;
      }
    }
    onActionEvent(event: PiPWindow.PiPActionEventType, status?: number) {
      switch (event) {
        case 'playbackStateChanged':
          if (status === 0) {
            this.avPlayerController?.videoPause();
          } else if (status === 1) {
            this.avPlayerController?.videoPlay();
          }
          break;
        default:
          break;
      }
    }
  3. Destroy the PiP controller, and call setAutoStartEnabled()(false) to disable the automatic activation of PiP mode.

    destroyPipController() {
      if (!this.pipController) {
        return;
      }
      this.pipController.setAutoStartEnabled(false);
      this.pipController.off('stateChange');
      this.pipController.off('controlPanelActionEvent');
      this.pipController = undefined;
    }

Integrating with the Media Controller

[h2]Scenario

The Media Controller is used to control the playback, pause, and switching between previous/next videos

[h2]How to Implement

Use AVSessionKit to implement integration with the Media Controller for video applications.

[h2]How to Develop

  1. Use createAVSession() to create an AVSession instance and activate the session. Set AVSessionType to video.

    public initAvSession() {
      this.context = AppStorage.get(KeyConstants.KEY_CONTEXT);
      if (!this.context) {
        Logger.error(TAG, 'session create failed : context is undefined');
        return;
      }
      avSession.createAVSession(this.context, 'LONG_VIDEO_SESSION', 'video').then(async (avSession) => {
        this.avSession = avSession;
        BackgroundTaskManager.startContinuousTask(this.context);
        this.setLaunchAbility();
        this.avSession.activate().catch((err: BusinessError) => {
          Logger.error(TAG, `avSession activate failed, code is ${err.code}, message is ${err.message}`);
        });
      }).catch((err: BusinessError) => {
        Logger.error(TAG, `createAVSession failed, code is ${err.code}, message is ${err.message}`);
      });
    }
  2. Call setAVMetadata() to provide metadata information for display in the Media Controller. The metadata includes the media ID (assetId), title (title), image displayed (mediaImage), and media duration (duration).

    public async setAVMetadata(curSource: VideoData, duration: number) {
      if (curSource === undefined) {
        Logger.error(TAG, 'SetAVMetadata Error, curSource is null');
        return;
      }
      let metadata: avSession.AVMetadata = {
        assetId: `${curSource.index}`,
        title: curSource.name,
        duration: duration
      };
      if (this.avSession) {
        this.avSession.setAVMetadata(metadata).then(() => {
          this.avSessionMetadata = metadata;
        }).catch((err: BusinessError) => {
          Logger.error(TAG, `SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
        });
      }
    }
  3. Set the UIAbility to be launched by the media controller.

    private setLaunchAbility() {
      if (!this.context) {
        return;
      }
      const wantAgentInfo: wantAgent.WantAgentInfo = {
        wants: [
          {
            bundleName: this.context.abilityInfo.bundleName,
            abilityName: this.context.abilityInfo.name
          }
        ],
        actionType: wantAgent.OperationType.START_ABILITIES,
        requestCode: 0,
        wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
      };
      wantAgent.getWantAgent(wantAgentInfo).then((agent) => {
        if (this.avSession) {
          this.avSession.setLaunchAbility(agent).catch((err: BusinessError) => {
            Logger.error(TAG, `setLaunchAbility failed: code: ${err.code}, message: ${err.message}`);
          });
        }
      }).catch((err: BusinessError) => {
        Logger.error(TAG, `getWantAgent failed: code: ${err.code}, message: ${err.message}`);
      });
    }
  4. Register a listener for playback control command events so that the application can respond to playback control commands delivered by the user through the Media Controller, such as on('play'), on('pause'), on('playPrevious'), and on('playNext').

    public async setAvSessionListener() {
      if (!this.avSessionController) {
        return;
      }
      try {
        this.avSessionController.getAvSession()?.on('play', () => this.sessionPlayCallback());
        this.avSessionController.getAvSession()?.on('pause', () => this.sessionPauseCallback());
        this.avSessionController.getAvSession()?.on('seek', (seekTime: number) => this.sessionSeekCallback(seekTime));
        this.avSessionController.getAvSession()?.on('setLoopMode', (mode: avSession.LoopMode) => {
          Logger.info(`on setLoopMode: ${mode}`);
        });
        this.avSessionController.getAvSession()?.on('playPrevious', () => {
          this.sessionPlayPreviousCallback();
        });
        this.avSessionController.getAvSession()?.on('playNext', () => {
          this.sessionPlayNextCallback();
        });
      } catch (exception) {
        Logger.error(TAG,
          `Invoke setAvSessionListener failed, code is ${exception.code}, message is ${exception.message}`);
      }
    }
  5. Call setAVPlaybackState() to report the video state information to the Media Controller for synchronization between the Media Controller and application. The information includes the playback state, position, and duration.

    private updateIsPlay() {
      this.avSessionController.setAvSessionPlayState({
        state: this.isPlaying ? avSession.PlaybackState.PLAYBACK_STATE_PLAY :
          avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
        position: {
          elapsedTime: this.currentTime,
          updateTime: new Date().getTime()
        },
        duration: this.durationTime,
        speed: this.curSpeed
      });
    }
    public setAvSessionPlayState(playbackState: avSession.AVPlaybackState) {
      if (this.avSession) {
        this.avSession.setAVPlaybackState(playbackState, (err: BusinessError) => {
          if (err) {
            Logger.error(TAG, `SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
          } else {
            Logger.info(TAG, 'SetAVPlaybackState successfully');
          }
        });
      }
    }

Background Playback

[h2]Scenario

Enable video playback to continue when the application moves to the background.

[h2]How to Implement

The implementation builds upon the integration with the media controller. It also requires requesting background running permissions, configuring the background mode, and creating a continuous background task.

Background playback depends on proper integration with the media controller. You should first complete the implementation steps outlined in Integrating with the Media Controller.

[h2]How to Develop

  1. In the module.json5 file, configure the ohos.permission.KEEP_BACKGROUND_RUNNING permission and the background mode audioPlayback.

    "requestPermissions": [
      {
        "name": "ohos.permission.KEEP_BACKGROUND_RUNNING",
        "reason": "$string:reason_background",
        "usedScene": {
          "abilities": [
            "AvplayerlongvideoAbility"
          ],
          "when": "always"
        }
      }
    ],
    "backgroundModes": [
      "audioPlayback"
    ],
  2. Create a background task management class to implement the application (startContinuousTask) and cancellation (stopContinuousTask) of background tasks. Set the continuous task type to AUDIO_PLAYBACK, indicating background video playback.

    public static startContinuousTask(context?: common.UIAbilityContext): void {
      if (!context) {
        return;
      }
      let wantAgentInfo: wantAgent.WantAgentInfo = {
        wants: [
          {
            bundleName: context.abilityInfo.bundleName,
            abilityName: context.abilityInfo.name
          }
        ],
        actionType: wantAgent.OperationType.START_ABILITY,
        requestCode: 0,
        wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
      };
      wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
        if (canIUse('SystemCapability.ResourceSchedule.BackgroundTaskManager.Core')) {
          backgroundTaskManager.startBackgroundRunning(context,
            backgroundTaskManager.BackgroundMode.AUDIO_PLAYBACK, wantAgentObj).then(() => {
          }).catch((err: BusinessError) => {
            Logger.error(TAG, `startBackgroundRunning failed, code is ${err.code}, message is ${err.message}`);
          });
        }
      }).catch((err: BusinessError) => {
        Logger.error(TAG, `getWantAgent failed, code is ${err.code}, message is ${err.message}`);
      });
    }
    public static stopContinuousTask(context?: common.UIAbilityContext): void {
      if (!context) {
        return;
      }
      if (canIUse('SystemCapability.ResourceSchedule.BackgroundTaskManager.Core')) {
        backgroundTaskManager.stopBackgroundRunning(context).then(() => {
        }).catch((err: BusinessError) => {
          Logger.error(TAG, `stopBackgroundRunning failed, code is ${err.code}, message is ${err.message}`);
        });
      }
    }
  3. During the creation of the AVSession, apply for a continuous background task. During the release of the AVSession, cancel the task.

    public initAvSession() {
      this.context = AppStorage.get(KeyConstants.KEY_CONTEXT);
      if (!this.context) {
        Logger.error(TAG, 'session create failed : context is undefined');
        return;
      }
      avSession.createAVSession(this.context, 'LONG_VIDEO_SESSION', 'video').then(async (avSession) => {
        this.avSession = avSession;
        BackgroundTaskManager.startContinuousTask(this.context);
        this.setLaunchAbility();
        this.avSession.activate().catch((err: BusinessError) => {
          Logger.error(TAG, `avSession activate failed, code is ${err.code}, message is ${err.message}`);
        });
      }).catch((err: BusinessError) => {
        Logger.error(TAG, `createAVSession failed, code is ${err.code}, message is ${err.message}`);
      });
    }
    async unregisterSessionListener() {
      if (!this.avSession) {
        return;
      }
      try {
        this.avSession.off('play');
        this.avSession.off('pause');
        this.avSession.off('playNext');
        this.avSession.off('playPrevious');
        this.avSession.off('setLoopMode');
        this.avSession.off('seek');
      } catch (exception) {
        Logger.error(TAG, `unregisterSessionListener failed: code: ${exception.code}, message: ${exception.message}`);
      }
      BackgroundTaskManager.stopContinuousTask(this.context);
    }

First Frame Display

[h2]Scenario

Enable the display of the first frame of a video in scenarios such as playback lists or playback windows.

[h2]How to Implement

[h2]How to Develop

To display the first frame of a video in the playlist, perform the following steps:

Use the fetchFrameByTime() method of the media.AVImageGenerator instance to obtain the first frame of a local video for display the list.

public static async getThumbnailFromVideo(src: string, timeUs: number) {
  let pixelMap: image.PixelMap | undefined;
  let queryOption = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC;
  let param: media.PixelMapParams = {
    width: 540,
    height: 304
  };
  let generator: media.AVImageGenerator | null = null;
  try {
    let fileDescriptor = await uiContext?.getHostContext()?.resourceManager?.getRawFd(src);
    if (!fileDescriptor) {
      Logger.error(TAG, 'Failed to get file descriptor');
      return null;
    }
    generator = await media.createAVImageGenerator();
    generator.fdSrc = fileDescriptor;
    pixelMap = await generator.fetchFrameByTime(timeUs, queryOption, param);
    await generator.release();
  } catch (exception) {
    Logger.error(TAG, `getThumbnailFromVideo failed, code is ${exception.code}, message is ${exception.message}`);
  }
  return pixelMap;
}

To display the first frame of a video in the playback window, perform the following steps:

  1. Ensure that the on('stateChange') method in the AVPlayer instance does not call this.avPlayer.play() in the prepared state. If this.avPlayer.play() is called, remove it to prevent the video from automatically playing after being loaded.

  2. In the on('stateChange') method, set showFirstFrameOnPrepare of setPlaybackStrategy to true in the initialized state.

    case 'initialized':
      Logger.info(TAG, 'setAVPlayerCallback AVPlayerState initialized called.');
      await this.onInitialized();
      break;
    private async onInitialized() {
      if (!this.avPlayer) {
        return;
      }
      this.avPlayer.surfaceId = this.surfaceID;
      try {
        await this.avPlayer.setPlaybackStrategy({
          preferredBufferDuration: 20,
          showFirstFrameOnPrepare: true
        });
      } catch (exception) {
        Logger.error(TAG,
          `setPlaybackStrategy failed. Cause code: ${exception.code}, message: ${exception.message}`);
      }
      this.avPlayer.prepare().catch((err: BusinessError) => {
        Logger.error(TAG, `prepare failed. Code:${err.code}, message:${err.message}`);
      });
    }

Orientation Switching and Rotation Detection

[h2]Scenario

Enable users to switch between the landscape and portrait modes during video playback.

[h2]How to Implement

[h2]How to Develop

To implement sensor-based automatic screen rotation, perform the following steps:

In the module-level configuration file module.json5, set the window display orientation to AUTO_ROTATION_RESTRICTED.

"orientation": "auto_rotation_restricted",

To implement manual orientation switching via button clicks, perform the following steps:

  1. Encapsulate the orientation switching method.

    setMainWindowOrientation(orientation: window.Orientation, callback?: Function): void {
      if (this.mainWindowClass === undefined) {
        Logger.error(TAG, 'MainWindowClass is undefined');
        return;
      }
      this.mainWindowClass.setPreferredOrientation(orientation).then(() => {
        callback?.();
      }).catch((err: BusinessError) => {
        Logger.error(TAG, `Failed to set the ${orientation} of main window. Code:${err.code}, message:${err.message}`);
      });
    }
  2. Set window.Orientation to USER_ROTATION_LANDSCAPE when the landscape playback button is tapped.

    this.windowUtil.setMainWindowOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  3. Set window.Orientation to USER_ROTATION_PORTRAIT when the back button is tapped.

    this.windowUtil.setMainWindowOrientation(window.Orientation.USER_ROTATION_PORTRAIT);

Seamless Video Transition

[h2]Scenario

Enable the video to continue playback from the original position without interruption after a switching between landscape and portrait modes.

[h2]How to Implement

Video playback is implemented based on AVPlayer and XComponent. When the screen orientation is switched between landscape and portrait, AVPlayer can continue playing the video from the original progress. Therefore, no additional development is required.

Sample Code

Long Video Playback Using AVPlayer