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 {
    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 {
    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.鸿蒙南向开发方向

相关推荐
Fibocom广和通7 分钟前
KES 2026|广和通LE270-KR获韩国KC认证并通过KT准入,助力智能电表等IoT应用落地
物联网
星恒讯工业路由器10 分钟前
5G RedCap、eRedCap与LTE Cat-1bis:中低速物联网的“三国杀“与选型指南
网络·智能路由器·工业路由器·工业物联网·5g redcap·lte cat-1bis·eredcap
乐讯通物联网服务商13 分钟前
LNG 运输船的船岸一体化通信:蜂窝物联网卡在近岸场景里解决了什么
物联网·物联网卡·lng 运输船
艾芯微科技13 分钟前
ETA1637S2G|钰泰同步升压 LED 背光驱动 SOT23-6,0.1% 超低占空比 PWM 调光
网络·单片机·嵌入式硬件·集成测试·51单片机
骑士雄师25 分钟前
食堂的节点和提示词的关系
ui·节点和提示词
右手吉他30 分钟前
高通平台IA APN问题分析之二
android·物联网
JosieBook44 分钟前
【多线程】两台机器同时抢一个字典:一次并发 Bug 的排查
java·网络·bug
Multipath7121 小时前
以多链路聚合为通信底座,让低空飞行器“连得上、传得快、飞得稳、管得住”
网络·5g·安全·智能路由器·实时音视频
乐讯通物联网服务商1 小时前
LTE 在物联网中的定位:Cat.1 / Cat.4 / Cat.M1 / NB-IoT 怎么选,物联网卡又该怎么配?
物联网·架构·物联网卡
hweiyu001 小时前
Redis命令:LPUSHX
redis·缓存