DEV Community

zhonghua
zhonghua

Posted on • Edited on

Practical Development of a Sports Video Player on HarmonyOS: Creating a Personalized Sports Video Player

Practical Development of a Sports Video Player on HarmonyOS: Creating a Personalized Sports Video Player

Core Technologies of HarmonyOS ## Sports Development ## Media Kit (Media Services)

In today's digital age, sports and fitness have become an integral part of many people's lives. Today, I will add a video player to the application to help users better warm up before exercising and stretch after exercising. This article will start from the core points of the code and guide you step by step to understand the key technologies and implementation details in the development process.

Image description

I. Project Background and Requirement Analysis

Before developing any application, clarifying the requirements is of vital importance. For a sports video player, we need to consider the following core functions:

  1. Video Playback: Support the playback of sports-related videos, such as warm-up and stretching.
  2. User Interaction: Provide simple button operations, such as play, pause, and resume.

II. Core Points of Code and Analysis

Next, we will go through the core parts of the code to gradually analyze the key steps in implementing the sports video player.

(I) Page Layout and Navigation

In HarmonyOS development, page layout is the foundation of user experience. We used LibNav and LibPage to build the navigation and content layout of the page. Here is the core part of the code:

@Component
export struct SportHelperPage {
  @Builder
  pageNavBuilder(){
    LibNav({
      pageTitle: "Sports Helper"
    }).width("100%")
  }

  @Builder
  pageContentBuilder(){
    Column() {
      Text('Sports Helper')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 20 })
      Button('Warm-up Before Running')
        .onClick(() => this.playVideo('https://video.111.com/p/bms/warmup_before_running.mp4'))
        .margin({ top: 10 })
      Button('Stretch After Running')
        .onClick(() => this.playVideo('https://video.111.com/p/bms/stretch_after_running.mp4'))
        .margin({ top: 10 })
      Button('Pause Playback')
        .onClick(() => {
          this.avPlayer?.pause()
        })
      Button('Resume Playback')
        .onClick(() => {
          this.avPlayer?.play()
        })
      XComponent({ type: XComponentType.SURFACE, controller: mXComponentController })
        .width('100%')
        .height(300)
    }
    .padding(20)
    .backgroundColor(Color.White)
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Page Navigation: By using LibNav, the page title is set to "Sports Helper", and its width is set to 100% to ensure that the navigation bar covers the entire top of the screen.
  2. Page Content: A Column layout is used to arrange text, buttons, and the video playback component (XComponent) in sequence. Each button is bound to a click event to trigger video playback or control the playback status.

(II) Initialization and Control of the Video Player

Video playback is the core function of the application, and we have used HarmonyOS's media.AVPlayer to implement it. Here is the code for initialization and playback control:

async initPlay() {
  try {
    this.avPlayer = await media.createAVPlayer();
    this.setAVPlayerCallback(this.avPlayer);
  } catch (error) {
    console.error('Failed to initialize video:', error);
  }
}

async playVideo(url: string) {
  try {
    if(this.avPlayer){
      this.avPlayer.url = url;
      this.avPlayer.play();
    }
  } catch (error) {
    console.error('Failed to play video:', error);
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Initialize Player: An AVPlayer instance is created through media.createAVPlayer(), and a callback function is registered to monitor changes in playback status.
  2. Play Video: By setting the avPlayer.url property to the video's URL and calling the play() method, playback begins. It should be noted that the video URL must be valid; otherwise, playback will fail.

(III) State Machine Callbacks and Error Handling

During video playback, various state changes and errors may occur. By registering callback functions, we can better manage these situations:

setAVPlayerCallback(avPlayer: media.AVPlayer) {
  avPlayer.on('startRenderFrame', () => {
    console.info(`AVPlayer start render frame`);
  });
  avPlayer.on('seekDone', (seekDoneTime: number) => {
    console.info(`AVPlayer seek succeeded, seek time is ${seekDoneTime}`);
  });
  avPlayer.on('error', (err: BusinessError) => {
    console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`);
    avPlayer.reset();
  });
  avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => {
    switch (state) {
      case 'idle':
        avPlayer.release();
        break;
      case 'initialized':
        const id = mXComponentController.getXComponentSurfaceId();
        avPlayer.surfaceId = id;
        avPlayer.prepare();
        break;
      case 'prepared':
        avPlayer.play();
        break;
      case 'paused':
        console.info('AVPlayer state paused called.');
        break;
      case 'completed':
        avPlayer.stop();
        break;
      case 'stopped':
        avPlayer.reset();
        break;
      case 'released':
        console.info('AVPlayer state released called.');
        break;
      default:
        console.info('AVPlayer state unknown called.');
        break;
    }
  });
}
Enter fullscreen mode Exit fullscreen mode
  1. State Callbacks: By listening to the stateChange event, we can perform corresponding actions based on different states (such as initialized, prepared, playing, etc.). For example, in the initialized state, set the surfaceId for the playback surface and call the prepare() method to prepare for playback.
  2. Error Handling: By listening to the error event, capture possible errors during playback and call the reset() method to reset the player's state.

III. Precautions and Optimization Suggestions in Development

During the development process, we need to pay attention to the following key points to ensure the stability of the application and the user experience:

  1. Validity of Video URLs: When calling the playVideo() method, the URL passed in must be valid. If the URL is invalid or the network is unavailable, the player will not work properly. It is recommended to validate the video URL in actual development and provide friendly error messages.
  2. Performance Optimization: To reduce video loading time, consider preloading video resources when the application starts. In addition, manage the player's lifecycle properly to avoid occupying system resources when it is not needed.
  3. User Experience: In page layout, the arrangement of buttons and text should be simple and clear, avoiding overly complex operations. Also, consider adding features such as a progress bar and volume control to further enhance the user experience.

IV. Conclusion

In actual development, developers can further expand the functions according to the requirements, such as adding more categories of sports videos and supporting offline downloads.

I'm sorry that I failed to parse the web pages you provided. The reason might be related to the web links or the network. You can check the validity of the web links and try again. If you have any other questions, feel free to ask.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.