简介
OhosVideoCache是一个支持边播放边缓存的库,只需要将音视频的url传递给OhosVideoCache处理之后再设置给播放器,OhosVideoCache就可以一边下载音视频数据并保存在本地,一遍读取本地缓存返回给播放器,使用者无需进行其他操作。OhosVideoCache还支持下载完成之后的断网播放,断点下载,会根据用户设置的参数自动清理缓存,避免手机里面存在过多的缓存文件占用磁盘空间,并且OhosVideoCache支持添加请求头和自定义缓存文件的命名。
下载安装
ohpm install @ohos/video-cache
使用说明
安装OhosVideoCache库之后,在需要使用的界面先导入OhosVideoCache提供的API
import {
HttpProxyCacheServer, HttpProxyCacheServerBuilder,CacheListener,FileNameGenerator ,HeaderInjector} from '@ohos/video-cache';
第一步 初始化代理服务器
建议将代理服务器设置为单例模式,整个工程只维护一个代理服务器对象,这样的好处是整个项目只维护一个代理服务器,不会生成多个服务器代理一个请求,造成资源、流量的浪费,降低应用的性能。
import common from '@ohos.app.ability.common';
import {
HttpProxyCacheServer } from '@ohos/video-cache';
export default class GlobalProxyServer {
private CONTEXT_STR: string = 'getContext';
private SERVER_STR: string = 'getServer';
private static instance: GlobalProxyServer;
private _objects: Map<string, Object | null> = new Map<string, Object | null>();
private constructor() {
}
public static getInstance(): GlobalProxyServer {
if (!GlobalProxyServer.instance) {
GlobalProxyServer.instance = new GlobalProxyServer()
}
return GlobalProxyServer.instance;
}
getContext(): common.UIAbilityContext {
return this._objects.get(this.CONTEXT_STR) as common.UIAbilityContext;
}
setContext(objectClass: common.UIAbilityContext) {
this._objects.set(this.CONTEXT_STR, objectClass);
}
getServer(): HttpProxyCacheServer {
return this._objects.get(this.SERVER_STR) as HttpProxyCacheServer;
}
setServer(objectClass: HttpProxyCacheServer) {
try {
let currentServer: HttpProxyCacheServer = this.getServer();
currentServer.shutdown()
} catch (err) {