#鸿蒙通关秘籍#如何在HarmonyOS中实现边播放边缓存视频?

HarmonyOS
2天前
浏览
收藏 0
回答 2
待解决
回答 2
按赞同
/
按时间
wuyanghcoa

如果你要在HarmonyOS中实现边播放边缓存视频,可以通过使用第三方库OhosVideoCache来实现哦,给个最基本的例子参考一下

// 引入必要的库和组件
import ohos.agp.components.*;
import ohos.agp.components.VideoPlayer;
import ohos.agp.render.VideoSurface;
import ohos.app.Context;
import ohos.multimodalinput.common.MultimodalEvent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.common.Source;
import ohos.media.player.Player;
import ohos.media.player.SourceHelper;
import ohos.media.player.VideoPlayerAgent;
import ohos.media.player.VideoPlayerConfig;

// 初始化视频播放器
private void initVideoPlayer() {
    VideoPlayerAgentConfig config = new VideoPlayerAgentConfig();
    videoPlayerAgent = VideoPlayerAgent.createVideoPlayerAgent(getContext(), config);
    videoPlayerAgent.setPlayerStateCallback(new PlayerStateCallback());
    // 设置视频播放地址
    Source source = SourceHelper.createVideoSource("your_video_url");
    videoPlayerAgent.setSource(source);
    // 开始播放
    videoPlayerAgent.play();
}

// 视频播放状态回调
class PlayerStateCallback extends PlayerStateCallback {
    @Override
    public void onPlayerStateChanged(int playerState) {
        super.onPlayerStateChanged(playerState);
        // 根据播放状态进行操作
    }
}

// 获取视频播放地址
private String getVideoUrl() {
    // 使用GlobalProxyServer获取代理URL
    return "your_video_url";
}

// 设置视频播放器URL并播放
private void setVideoPlayerUrlAndPlay(String url) {
    Source source = SourceHelper.createVideoSource(url);
    videoPlayerAgent.setSource(source);
    videoPlayerAgent.play();
}
分享
微博
QQ
微信
回复
2天前
DB风痕

在HarmonyOS中实现边播放边缓存视频可以通过使用OhosVideoCache库。以下是实现步骤:

  1. 初始化XComponent组件:用于绘制视频播放窗口。通过onLoad函数来调用VideoPlayerManager中的initPlayer方法,创建音视频管理实例。

    XComponent({
       id: 'xcomponent',
       type: 'surface',
       controller: this.componentController
     })
       .height(`${this.xComponentHeight}px`)
       .width(`${this.xComponentWidth}px`)
       .onLoad(() => {
         this.componentController.setXComponentSurfaceSize({
           surfaceWidth: SURFACE_WIDTH,
           surfaceHeight: SURFACE_HEIGHT
         });
         this.surfaceId = this.componentController.getXComponentSurfaceId();
         AvPlayManager.getInstance()
           .initPlayer(getContext(this) as common.UIAbilityContext, this.surfaceId, (avPlayer: media.AVPlayer) => {
             avPlayer.on('timeUpdate', (time: number) => {
               this.currentTime = time;
             });
             this.videoDuration = handleTime(avPlayer.duration);
             this.total = avPlayer.duration;
           })
       })
    
  2. 初始化代理服务器:使用setServer方法初始化代理服务器。此服务器用来处理音视频URL。

    import common from '@ohos.app.ability.common';
    import { HttpProxyCacheServer } from '@ohos/video-cache';
    
    const CONTEXT_STR: string = 'context';
    const SERVER_STR: string = 'server';
    
    export default class GlobalProxyServer {
      private static instance: GlobalProxyServer | null = null;
      private objects: Map<string, Object | null> = new Map<string, Object | null>();
    
      public static getInstance(): GlobalProxyServer {
        if (!GlobalProxyServer.instance) {
          GlobalProxyServer.instance = new GlobalProxyServer();
        }
        return GlobalProxyServer.instance;
      }
      ...
      setServer(objectClass: HttpProxyCacheServer): void {
        try {
          const currentServer: HttpProxyCacheServer = this.getServer();
          currentServer.shutdown();
        } catch (err) {
        }
        this.objects.set(SERVER_STR, objectClass);
      }
    }
    
  3. 管理和播放媒体资源:通过media.createAVPlayer()创建播放管理类。

    async initPlayer(context: common.UIAbilityContext, surfaceId: string,
                       callback: (avPlayer: media.AVPlayer) => void): Promise<void> {
        this.surfaceID = surfaceId;
        try {
          this.avPlayer = await media.createAVPlayer();
          await this.setAVPlayerCallback(callback);
          this.cacheAndPlayVideo(context);
        } catch (err) {
          logger.error(`initPlayer initPlayer err:${JSON.stringify(err)}`);
        }
      }
    
  4. 边播放边缓存:通过MyCacheListener监听缓存进度,使用getProxyUrl(ORIGIN_URL)获取视频播放地址,并设置给播放器。

    async cacheAndPlayVideo(context: common.UIAbilityContext): Promise<void> {
      class MyCacheListener implements CacheListener {
        onCacheAvailable(cacheFilePath: string, url: string, percentsAvailable: number): void {
          AppStorage.setOrCreate('currentCachePercent', percentsAvailable);
        }
      }
    
      GlobalProxyServer?.getInstance()?.getServer()?.registerCacheListener(new MyCacheListener(), ORIGIN_URL);
      let proxyUrl: string | undefined = await GlobalProxyServer?.getInstance()?.getServer()?.getProxyUrl(ORIGIN_URL);
      if (proxyUrl.startsWith(context.cacheDir)) {
        const file = fs.openSync(proxyUrl, fs.OpenMode.READ_ONLY);
        proxyUrl = `fd://${file.fd}`;
      }
      this.avPlayer.url = proxyUrl;
    }
    
分享
微博
QQ
微信
回复
2天前
相关问题
HarmonyOS 如何实现文字描效果
349浏览 • 0回复 待解决