HarmonyOS 应用开发-边缓存边播放案例

介绍

OhosVideoCache是一个支持边播放边缓存的库,只需要将音视频的url传递给OhosVideoCache处理之后再设置给播放器,

OhosVideoCache就可以一边下载音视频数据并保存在本地,一边读取本地缓存返回给播放器,使用者无需进行其他操作。

效果图预览

使用说明

  1. 进入页面,自动播放视频,点击暂停,视频停止播放,点击播放,视频继续播放。
  2. 视频播放完成之后,点击播放按钮,视频重新播放。

实现思路

边缓存播放功能主要是通过Xcomponent组件、@ohos.multimedia.media以及OhosVideoCache三方库实现,XComponent组件主要用于绘制

视频播放的窗口,页面进来初始化服务器然后利用XComponent组件的onLoad函数来调用 VideoPlayerManager

中的initPlayer方法创建一个音视频管理实例,并通过setAVPlayerCallback函数和cacheAndPlayVideo函数来实现视频状态的监听以及边缓存边播放功能。

  1. XComponent组件绘制视频播放窗口。

    XComponent({
    id: 'xcomponent',
    type: 'surface',
    controller: this.componentController
    })
    .height(${this.xComponentHeight}px)
    .width(${this.xComponentWidth}px)
    .onLoad(() => {
    // 设置XComponent持有Surface的宽度和高度
    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;
    }
    /**
    * 获取上下文信息
    * @returns
    /
    getContext(): common.UIAbilityContext {
    return this.objects.get(CONTEXT_STR) as common.UIAbilityContext;
    }
    /
    *
    * 设置上下文信息
    * @param context
    */
    setContext(context: common.UIAbilityContext): void {
    this.objects.set(CONTEXT_STR, context);
    }

    /**
    * 获取服务器
    * @returns
    */
    getServer(): HttpProxyCacheServer {
    return this.objects.get(SERVER_STR) as HttpProxyCacheServer;
    }

    /**
    * 设置服务器
    * @param objectClass
    */
    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> {
    logger.info(TAG, initPlayer==initCamera surfaceId== ${surfaceId});
    this.surfaceID = surfaceId;
    try {
    // 创建avPlayer实例对象
    this.avPlayer = await media.createAVPlayer();
    // 创建状态机变化回调函数
    await this.setAVPlayerCallback(callback);
    // 边缓存边播放
    this.cacheAndPlayVideo(context);
    } catch (err) {
    logger.error(TAG, initPlayer initPlayer err:${JSON.stringify(err)});
    }
    }

  4. 边播放边缓存,MyCacheListener监听缓存进度,getProxyUrl(ORIGIN_URL)获取视频播放地址并设置给播放器。

    /**
    * 边缓存边监听函数
    * @param context 上下文信息
    * @returns
    */
    async cacheAndPlayVideo(context: common.UIAbilityContext): Promise<void> {
    logger.info(TAG, cacheAndPlayVideo start);

    复制代码
     // TODO:知识点:监听缓存进度
     class MyCacheListener implements CacheListener {
       onCacheAvailable(cacheFilePath: string, url: string, percentsAvailable: number): void {
         AppStorage.setOrCreate('currentCachePercent', percentsAvailable);
       }
     }
    
     GlobalProxyServer?.getInstance()?.getServer()?.registerCacheListener(new MyCacheListener(), ORIGIN_URL);
     // TODO:知识点:将原始的音视频url交给OhosVideoCache
     let proxyUrl: string | undefined = await GlobalProxyServer?.getInstance()?.getServer()?.getProxyUrl(ORIGIN_URL);
     // 由于avplayer不支持直接加载本地文件路径 这里需要转化为fd的路径
     if (proxyUrl.startsWith(context.cacheDir)) {
       const file = fs.openSync(proxyUrl, fs.OpenMode.READ_ONLY);
       proxyUrl = `fd://${file.fd}`;
     }
     logger.info(TAG, `proxyUrl ${proxyUrl}`);
     // 将处理之后的url设置给播放器
     this.avPlayer.url = proxyUrl;

    }

高性能知识点

不涉及。

工程结构&模块类型

复制代码
videocache                                         // har类型
|---model
|   |---GlobalProxyServer.ets                      // 模型层-服务器管理
|   |---VideoPlayerManager.ets                     // 模型层-音视频管理
|---utils
|   |---utils.ets                                  // 工具
|---view
|   |---VideoCacheView.ets                         // 视图层-应用主页面

为了能让大家更好的学习鸿蒙(HarmonyOS NEXT)开发技术,这边特意整理了《鸿蒙开发学习手册》(共计890页),希望对大家有所帮助:https://qr21.cn/FV7h05

《鸿蒙开发学习手册》:

如何快速入门:https://qr21.cn/FV7h05

  1. 基本概念
  2. 构建第一个ArkTS应用
  3. ......

开发基础知识:https://qr21.cn/FV7h05

  1. 应用基础知识
  2. 配置文件
  3. 应用数据管理
  4. 应用安全管理
  5. 应用隐私保护
  6. 三方应用调用管控机制
  7. 资源分类与访问
  8. 学习ArkTS语言
  9. ......

基于ArkTS 开发:https://qr21.cn/FV7h05

  1. Ability开发
  2. UI开发
  3. 公共事件与通知
  4. 窗口管理
  5. 媒体
  6. 安全
  7. 网络与链接
  8. 电话服务
  9. 数据管理
  10. 后台任务(Background Task)管理
  11. 设备管理
  12. 设备使用信息统计
  13. DFX
  14. 国际化开发
  15. 折叠屏系列
  16. ......

鸿蒙开发面试真题(含参考答案):https://qr18.cn/F781PH

鸿蒙开发面试大盘集篇(共计319页):https://qr18.cn/F781PH

1.项目开发必备面试题

2.性能优化方向

3.架构方向

4.鸿蒙开发系统底层方向

5.鸿蒙音视频开发方向

6.鸿蒙车载开发方向

7.鸿蒙南向开发方向

相关推荐
TeleostNaCl12 分钟前
解决 Chrome 无法访问网页但无痕模式下可以访问该网页 的问题
前端·网络·chrome·windows·经验分享
!chen1 小时前
k8s-Pod中的网络通信
网络·docker·kubernetes
JJCar3 小时前
【Cache缓存】cache的刷新
缓存·cache·多核数据一致性
wdfk_prog4 小时前
便携式功耗分析仪LuatOS IoT Power vs. Nordic PPK2
物联网
悲伤小伞5 小时前
Linux_Socket_UDP
linux·服务器·网络·c++·网络协议·udp
学网络的APang5 小时前
Apache HTTP Server 2.4.65 详细安装教程(基于 CentOS 7)
运维·网络
FreeBuf_6 小时前
SesameOp 恶意软件滥用 OpenAI Assistants API 实现与 C2 服务器的隐蔽通信
运维·服务器·网络
瘦马7 小时前
PhotoShop网页版(在线ps)在快速修复老照片,在线修旧如新
ui·photoshop·photoshop网页版·在线p图
极造数字7 小时前
从EMS看分布式能源发展:挑战与机遇并存
人工智能·分布式·物联网·信息可视化·能源·制造
tt5555555555557 小时前
Transformer原理与过程详解
网络·深度学习·transformer