OpenHarmony3.1新特性-surface+videoplayer实现视频播放
千呼万唤始出来,在OpenHarmony最新发布的3.1版本中终于支持了surface+videoplayer实现视频播放的功能。
1. surface+videoplayer视频播放与传统的video组件对比
大家可能觉得不是很早就支持一个video组件就可以实现视频播放吗?是的,video组件也就简简单单能做个视频播放,而你仔细去查阅下,video组件支持的api功能太少了,很多定制化功能都无法实现。下面是3.1版本上video组件所具备的api:
而在3.1中添加了一个关键组件就是xcomponent,它可以设置一个type为surface,而我更关心的就是这个surface,在讲surface之前我先讲讲videoplayer。
3.1版本中同时还新增了视频播放的媒体服务videoplayer,它为我们提供了视频播放服务相关的各种api,video组件所具备的功能它全部具备,同时还具备视频首帧送显上报事件、监听视频播放宽高变化事件、监听视频缓存更新事件等等高级功能,这样就可以帮助我们自定义出非常高级的视频播放器出来了。
而videoplayer它只是个做视频播放的媒体服务,它并不能直接项video组件那样输出视频显示在显示器上,这个时候就需要借助surface了。Surface可以简单的理解为绘制时用的画布,在hml布局文件中添加一个xcomponent组件并设置type为surface,就相当于放置了一块画布。而surface在程序中可以抽象为一块内存,在js代码中xcomponent组件通过调用getXComponentSurfaceId()方法可以申请这块内存,然后就可以随意的绘制,videoplayer在完成视频的编解码服务之后,可以通过调用setDisplaySurface这个方法将视频内容输出到之前的surface内存中,从而达到最终视频在窗口上显示的功能。下图是基本架构图
2. surface+videoplayer视频播放代码实现
下面只实现一个最基础的视频播放功能。
首先是编写hml布局文件,代码如下:
然后编写js文件,代码如下:
import media from '@ohos.multimedia.media'import fileIO from '@ohos.fileio'let videoPlayer = undefined;let surfaceID = undefined; // 用于保存Xcomponent接口返回的surfaceIDexport default { data: { title: "" }, onInit() { }, // 调用Xcomponent的接口用于获取surfaceID,并保存在surfaceID变量中,该接口由XComponent组件默认加载,非主动调用 async LoadXcomponent() { surfaceID = this.$element('Xcomponent').getXComponentSurfaceId(); console.info('LoadXcomponent surfaceID is' + surfaceID); // 用户选择视频设置fd(本地播放) let fdPath = 'fd://'; // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" 命令,将其推送到设备上 let path = '/data/accounts/account_0/appdata/1.mp4'; await fileIO.open(path).then(fdNumber => { fdPath = fdPath + '' + fdNumber; console.info('open fd sucess fd is' + fdPath); }, err => { console.info('open fd failed err is' + err); }); await media.createVideoPlayer().then((video) => { if (typeof (video) != 'undefined') { videoPlayer = video; console.info('video createVideoPlayer success'); } else { console.info('video createVideoPlayer fail'); } }).catch((error) => { console.info(`video catchCallback, error:${error.message}`); }); videoPlayer.url = fdPath; console.info('video url success'); // 设置surfaceID用于显示视频画面 await videoPlayer.setDisplaySurface(surfaceID).then(() => { console.info('setDisplaySurface success'); }).catch((error) => { console.info(`video catchCallback, error:${error.message}`); }); // 调用prepare完成播放前准备工作 await videoPlayer.prepare().then(() => { console.info('prepare success'); }).catch((error) => { console.info(`video catchCallback, error:${error.message}`); }); // 调用play开始播放 await videoPlayer.play().then(() => { console.info('play success'); }).catch((error) => { console.info(`video catchCallback, error:${error.message}`); }); },}