HarmonyOS application development-video player and pop-up window

Viedo component

On terminal devices such as mobile phones, tablets or smart screens, media functions can be counted as one of our most commonly used scenarios. Whether it is to implement audio playback, recording, collection, video playback, switching, looping, or camera preview, photo taking and other functions, media components are indispensable. Taking the video function as an example, during the application development process, we need to add basic video playback functions to the application through the Video component provided by ArkUI. With the Video component, we can implement the video playback function and control its playback status. Common video playback scenarios include watching popular short videos on the Internet, as well as viewing our locally stored video content.

Constructor

Video(value: {<!-- -->src?: string | Resource, currentProgressRate?: number | string |PlaybackSpeed, previewUri?: string |PixelMap | Resource, controller?: VideoController})
Parameter name Parameter type Is it required? Description
src string | Resource No The path of the video playback source, which can be a local video path or a network path. You can also use the media library management module to query video files in the public media library.
currentProgressRate number No Video playback speed, supports 0.75, 1.0, 1.25, 1.75, 2.0, the default value is 1.0 times speed.
previewUri string | PixelMap8 + | Resource No Preview image path or resource when the video is not playing.
controller VideoController No Video controller, used to control video playback and other related functions.
@Component
export default struct VideoPlayer {<!-- -->
  private source: string | Resource;
  private controller: VideoController;

  build() {<!-- -->
    Column() {<!-- -->
      Video({<!-- -->
        src: this.source,
        controller: this.controller
      })
    }
  }
}

Component properties

Parameter name Parameter type Is it required? Default value Description
muted boolean No false Whether to mute.
autoPlay boolean No false Whether to play automatically.
controls boolean No true Whether the control bar that controls video playback is displayed.
objectFit ImageFit No Cover Set the video display mode (optional values: Contain, Cover, Auto, Fill, ScaleDown, None).
loop boolean No false Whether a single video plays in a loop.
@Component
export default struct VideoPlayer {<!-- -->
  private source: string | Resource;
  private controller: VideoController;

  build() {<!-- -->
    Column() {<!-- -->
      Video({<!-- -->
        src: this.source,
        controller: this.controller
      })
        .controls(false) //Do not display the control bar
        .autoPlay(false) // Manually click to play
        .loop(false) // Turn off loop playback
    }
  }
}
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">

Event

Event handler Parameter type Description
onStart(event: () => void) No parameters This event is triggered during playback and the specified callback function is executed.
onPause(event: () => void) No parameters This event is triggered when paused and the specified callback function is executed.
onFinish(event: () => void) No parameters This event is triggered when playback ends and the specified callback function is executed.
onError(event: () => void) No parameters This event is triggered when playback fails and the specified callback function is executed.
onPrepared(callback: (event?: { duration: number }) => void) event Optional parameters: { duration: number } This event is triggered when the video preparation is completed, and the video duration is obtained through the duration parameter.
onSeeking(callback: (event?: { time: number }) => void) event Optional parameters: { time: number } Report time information during the operation of the progress bar, in seconds.
onSeeked(callback: (event?: { time: number }) => void) event Optional parameters: { time: number } After the operation progress bar is completed, the playback time information is reported, in seconds.
onUpdate(callback: (event?: { time: number }) => void) event Optional parameters: { time: number } This event is triggered when the playback progress changes. The unit is seconds and the update interval is 250 milliseconds.
onFullscreenChange(callback: (event?: { fullscreen: boolean }) => void) event Optional parameters: { fullscreen: boolean } This event is triggered when switching between full-screen playback and non-full-screen playback status.

Dialog component

Pop-up window type Brief description
Confirmation pop-up window (AlertDialog) is used to display warnings to users or require users to confirm operations. The user must make a selection or cancel the dialog box before continuing.
Selection pop-up window (TextPickerDialog, DatePickerDialog, TimePickerDialog) is used when the user needs to select text, Provides a convenient selection interface for date or time. Users can choose from predefined options.
Customized pop-up window (CustomDialog) If the built-in pop-up window type cannot meet your needs, You can create custom popups to meet your specific business needs. This allows you to have full control over the layout and style of your popup.

Warning pop-up window

Button('Click to display the pop-up window')
  .onClick(() => {<!-- -->
    AlertDialog.show(
      {<!-- -->
        title: 'Delete Contact', // title
        message: 'Do you need to delete the selected contact?', // content
        autoCancel: false, // Whether to close the pop-up window when clicking on the barrier layer.
        alignment: DialogAlignment.Bottom, // The vertical alignment of the pop-up window
        offset: {<!-- --> dx: 0, dy: -20 }, // The offset of the pop-up window relative to the alignment position
        primaryButton: {<!-- -->
          value: 'cancel',
          action: () => {<!-- -->
            console.info('Callback when the first button is clicked');
          }
        },
        secondaryButton: {<!-- -->
          value: 'delete',
          fontColor: '#D94838',
          action: () => {<!-- -->
            console.info('Callback when the second button is clicked');
          }
        },
        cancel: () => {<!-- --> //Callback when clicking the barrier layer to close the dialog
          console.info('Closed callbacks');
        }
      }
    )
  })
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">

The following is a table description of the properties and their functions in the AlertDialog pop-up window sample code:

Attribute Function
title The pop-up window title is usually used to briefly describe the purpose or content of the pop-up window.
message Pop-up message content, usually used to provide more detailed information or guide user operations.
autoCancel Specify whether to close the pop-up window when clicking on the barrier layer, if set to true, clicking the barrier layer will close the pop-up window, otherwise it will not.
alignment The vertical alignment of the pop-up window, here set to DialogAlignment .Bottom means that the pop-up window appears at the bottom.
offset The offset of the pop-up window relative to the alignment position, Here { dx: 0, dy: -20 } means a vertical offset of -20 pixels.
primaryButton Primary button configuration, including button text and callback function when the button is clicked.
secondaryButton Secondary button configuration, including button text, button font color and callback when the button is clicked function.
cancel Callback function when clicking on the barrier layer to close the pop-up window, usually used to perform additional Close the operation.

This table provides the properties used in the sample code and their functions. These properties allow you to customize the popup’s appearance and behavior to suit your application’s needs. If you need more information or have additional questions, please feel free to ask.

Text selection pop-up window

TextPickerDialog.show({<!-- -->
            range: this.fruits, // Set the selection range of the text selector
            selected: this.select, // Set the index value of the initial selected item.
            onAccept: (value: TextPickerResult) => {<!-- --> // This callback is triggered when the "OK" button in the pop-up window is clicked.
              // Set select to the index of the selected item when the OK button is pressed, so that when the pop-up window pops up again, it will show that the last selected option is selected.
              this.select = value.index;
              console.info("TextPickerDialog:onAccept()" + JSON.stringify(value));
            },
            onCancel: () => {<!-- --> // This callback is triggered when the "Cancel" button in the pop-up window is clicked.
              console.info("TextPickerDialog:onCancel()");
            },
            onChange: (value: TextPickerResult) => {<!-- --> // This callback is triggered when the selector in the sliding pop-up window changes the currently selected item.
              console.info("TextPickerDialog:onChange()" + JSON.stringify(value));
            }
          })
        })
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">
Configuration options Function
range Sets the selection range of the text selector, which is the list of options the user can choose from.
selected Set the index value of the initial selected item. This ensures that the last selected option is selected when the pop-up window is displayed.
onAccept Callback function, triggered when the user clicks the “OK” button in the pop-up window , allowing related operations to be performed.
onCancel Callback function, triggered when the user clicks the “Cancel” button in the pop-up window , allowing related operations to be performed.
onChange Callback function, when the user slides on the selector in the pop-up window to change Triggered when an item is currently selected, allowing related operations to be performed.

Date selection box

DatePickerDialog.show({<!-- -->
            start: new Date("1900-1-1"), // Set the start date of the selector
            end: new Date("2023-12-31"), // Set the end date of the selector
            selected: this.selectedDate, // Set the currently selected date
            lunar: false,
            onAccept: (value: DatePickerResult) => {<!-- --> // This callback is triggered when the "OK" button in the pop-up window is clicked
              // Use the setFullYear method of Date to set the date when the OK button is pressed, so that when the pop-up window pops up again, it will display that the last confirmed date is selected.
              this.selectedDate.setFullYear(value.year, value.month, value.day)
              console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
            },
            onCancel: () => {<!-- --> // This callback is triggered when the "Cancel" button in the pop-up window is clicked
              console.info("DatePickerDialog:onCancel()")
            },
            onChange: (value: DatePickerResult) => {<!-- --> // This callback is triggered when the sliding selector in the sliding pop-up window changes the currently selected item.
              console.info("DatePickerDialog:onChange()" + JSON.stringify(value))
            }
          })
        })
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">
Configuration options Function
start Set the start date of the selector from which the user can select.
end Set the end date of the selector from which the user can choose.
selected Set the currently selected date to ensure that when the pop-up window pops up again, the selected date is The date of the last determination.
lunar Boolean value indicating whether to use lunar dates.
onAccept Callback function, triggered when the user clicks the “OK” button in the pop-up window , allowing related operations to be performed.
onCancel Callback function, triggered when the user clicks the “Cancel” button in the pop-up window , allowing related operations to be performed.
onChange Callback function, when the user slides on the sliding selector in the pop-up window to Triggered when the currently selected date is changed, allowing related operations to be performed.

Customized pop-up box

@CustomDialog
export default struct CustomDialogWidget {<!-- -->
  @State hobbyBeans: HobbyBean[] = [];
  @Link hobbies: string;
  private controller: CustomDialogController;

  aboutToAppear() {<!-- -->...}

  setHobbiesValue(hobbyBeans: HobbyBean[]) {<!-- -->
    let hobbiesText: string = '';
    hobbiesText = hobbyBeans.filter((isCheckItem: HobbyBean) =>
    isCheckItem?.isChecked)
      .map((checkedItem: HobbyBean) => {<!-- -->
        return checkedItem.label;
      }).join(',');
    this.hobbies = hobbiesText;
  }

  build() {<!-- -->
    Column() {<!-- -->
      Text($r('app.string.text_title_hobbies'))...
      List() {<!-- -->
        ForEach(this.hobbyBeans, (itemHobby: HobbyBean) => {<!-- -->
          ListItem() {<!-- -->
            Row() {<!-- -->
              Text(itemHobby.label)...
              Toggle({<!-- --> type: ToggleType.Checkbox, isOn: false })...
                .onChange((isCheck) => {<!-- -->
                  itemHobby.isChecked = isCheck;
                })
            }
          }
        }, itemHobby => itemHobby.label)
      }

      Row() {<!-- -->
        Button($r("app.string.cancel_button"))...
          .onClick(() => {<!-- -->
            this.controller.close();
          })
        Button($r("app.string.definite_button"))...
          .onClick(() => {<!-- -->
            this.setHobbiesValue(this.hobbyBeans);
            this.controller.close();
          })
      }
    }
  }
}
customDialogController: CustomDialogController = new CustomDialogController({<!-- -->
    builder: CustomDialogWidget({<!-- -->
      onConfirm: this.setHobbiesValue.bind(this),
    }),
    alignment: DialogAlignment.Bottom,
    customStyle: true,
    offset: {<!-- --> dx: 0,dy: -20 }
  });
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">
Steps Instructions
1. Create a custom pop-up component Create a new component and identify it as a custom pop-up component.
2. Define component appearance and behavior Define the appearance and layout of the pop-up window in the pop-up window component and behaviors, including buttons and callbacks.
3. Create a pop-up window controller Create a pop-up window controller to manage pop-up windows display and close.
4. Configure the pop-up window controller Configure the appearance and appearance of the pop-up window in the pop-up window controller Style, such as position, size, etc.
5. Display a pop-up window Use the controller method to display a custom pop-up window, usually through show method triggers.
6. Process user operations Define a callback function in the pop-up component to process user operations Actions, such as button clicks.
7. Close the pop-up window Use the controller method in the pop-up window component to close the pop-up window. Usually through the close method.
8. Complete and test Make sure the custom popup works as expected, test it, make sure everything normal.