#鸿蒙通关秘籍#如何在鸿蒙视频播放器中实现播放信息的持久化?

HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
HTTPS寒光闪闪

为实现播放信息的持久化,可使用 @ohos.data.preferences 来存储和读取用户的播放状态。在每次发布事件时,调用存储方法持久化当前播放信息。在页面首次加载时,从持久化存储中读取播放信息并显示到界面上。以下代码示例展示了如何实现:

import preferences from '@ohos.data.preferences'
import { videoDefaultState, VideoPlayStateType } from '../models/videoPlayState'

export class PreferencesClass {
  StoreName = 'VIDEO_PLAYER'
  context: Context

  VideoPlayStateKey = "VIDEO_PLAY_STATE"

  constructor(context: Context) {
    this.context = context
  }

  async getStore() {
    return await preferences.getPreferences(this.context, this.StoreName)
  }

  async setVideoPlayState(playState: VideoPlayStateType) {
    const store = await this.getStore()
    await store.put(this.VideoPlayStateKey, JSON.stringify(playState))
    await store.flush()
  }

  async getVideoPlayState(): Promise<VideoPlayStateType> {
    const store = await this.getStore()
    return JSON.parse(await store.get(this.VideoPlayStateKey, JSON.stringify(videoDefaultState)) as string) as VideoPlayStateType
  }
}
import media from '@ohos.multimedia.media'

export class VideoAVPlayerClass {
  static player: media.AVPlayer | null = null
  static duration: number = 0
  static time: number = 0
  static isPlay: boolean = false
  static playList: videoItemType[] = []
  static playIndex: number = 0
  static surfaceId: string = ''
  static context: Context | null = null

  static async init(initParams: InitParams) {
    VideoAVPlayerClass.avPlayer = await media.createAVPlayer()
    VideoAVPlayerClass.context = initParams.context
  }

  static async updateState() {
    const preferences = new PreferencesClass(VideoAVPlayerClass.context)
    await preferences.setVideoPlayState({
      duration: VideoAVPlayerClass.duration,
      time: VideoAVPlayerClass.time,
      isPlay: VideoAVPlayerClass.isPlay,
      playIndex: VideoAVPlayerClass.playIndex,
      playList: VideoAVPlayerClass.playList,
    })
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
使用AVPlayer实现视频播放器
1155浏览 • 1回复 待解决
HarmonyOS 点播视频播放器选型咨询
178浏览 • 1回复 待解决