当前位置: 首页 > news >正文

HarmonyOS 应用开发《掌上英语》第99篇:使用AVPlayer设置播放URL(ArkTS)

使用AVPlayer设置播放URL(ArkTS)

本开发指导将介绍如何使用AVPlayer开发播放功能,在不同的场景下如何设置URL。

当前指导仅介绍播放URL设置方法,其他场景及完整示例代码,请参考视频播放。

当前开发指导将提供以下设置播放URL的方法:

  • 流媒体播放场景下设置URL
  • 本地Raw文件播放场景下设置URL

流媒体播放场景下设置URL

情况一:播放HTTP/HTTPS媒体资源

import{media}from'@kit.MediaKit';// 类成员定义avPlayer。privateavPlayer:media.AVPlayer|null=null;// 在业务函数中(示例工程函数名为avSetupURL):// 创建avPlayer实例对象。this.avPlayer=awaitmedia.createAVPlayer();// 设置对应的播放url。leturl='https://xxx.xxx.xxx.mp4';if(this.avPlayer==null){return;}this.avPlayer.url=url;

情况二:HLS媒体资源播放(点播/直播)

import{media}from'@kit.MediaKit';// 类成员定义avPlayer。privateavPlayer:media.AVPlayer|null=null;// 在业务函数中(示例工程函数名为avSetupURL):// 创建avPlayer实例对象。this.avPlayer=awaitmedia.createAVPlayer();// 设置对应的播放url。leturl='https://xxx.xxx.xxx.xxx:xx/xx/index.m3u8';if(this.avPlayer==null){return;}this.avPlayer.url=url;

情况三:设置HTTP请求头信息播放

当服务器需要校验HTTP请求头信息时,可通过createMediaSourceWithUrl设置HTTP请求头信息。

import{media}from'@kit.MediaKit';// 类成员定义avPlayer。privateavPlayer:media.AVPlayer|null=null;// 在业务函数中(示例工程函数名为avSetupURL):// 创建avPlayer实例对象。this.avPlayer=awaitmedia.createAVPlayer();// 设置对应的播放url。leturl='https://xxx.xxx.xxx.xxx:xx/xx/index.m3u8';// 创建mediaSource实例对象,设置媒体来源,定制HTTP请求,如需要,可以键值对的形式设置User-Agent、Cookie、Referer等字段。letmediaSource:media.MediaSource=media.createMediaSourceWithUrl(url,{"User-Agent":"User-Agent-Value","Cookie":"Cookie-Value","Referer":"Referer-Value"});// 设置播放策略,设置缓冲区数据量为3s。letplaybackStrategy:media.PlaybackStrategy={preferredWidth:1,preferredHeight:2,preferredBufferDuration:3,preferredHdr:false};// 为avPlayer设置媒体来源和播放策略。this.avPlayer.setMediaSource(mediaSource,playbackStrategy);

情况四:通过本地Raw文件中的m3u8文件播放在线流媒体资源

当应用需要通过解析本地Raw文件中的m3u8文件,播放在线流媒体资源时,可以通过resourceManager.getRawFd获取文件描述符,将其拼接成fdUrl,并通过setMimeType设置MIME类型为APPLICATION_M3U8。

import{media}from'@kit.MediaKit';import{common}from'@kit.AbilityKit';// 类成员定义avPlayer和context。privateavPlayer:media.AVPlayer|null=null;privatecontext:common.UIAbilityContext|undefined=undefined;// 在业务函数中(示例工程函数名为avSetupURL):// 创建avPlayer实例对象。this.avPlayer=awaitmedia.createAVPlayer();this.context=this.getUIContext().getHostContext()ascommon.UIAbilityContext;// 通过本地m3u8文件名,获取文件描述符。letfileDescriptor=awaitthis.context.resourceManager.getRawFd('xxx.m3u8');// 用文件描述符构造本地m3u8的URL。letfdUrl:string="fd://"+fileDescriptor.fd+"?offset="+fileDescriptor.offset+"&size="+fileDescriptor.length;// 按需设置HTTP请求头。letheaders:Record<string,string>={"User-Agent":"User-Agent-Value","Cookie":"Cookie-Value"};// 通过本地m3u8的URL和HTTP请求头构造mediaSource媒体来源。letmediaSource:media.MediaSource=media.createMediaSourceWithUrl(fdUrl,headers);// 设置媒体MIME类型为APPLICATION_M3U8。letmimeType:media.AVMimeTypes=media.AVMimeTypes.APPLICATION_M3U8;mediaSource?.setMimeType(mimeType);// 设置播放策略,设置缓冲区数据量为20s。letplaybackStrategy:media.PlaybackStrategy={preferredBufferDuration:20};// 为avPlayer设置媒体来源和播放策略。this.avPlayer.setMediaSource(mediaSource,playbackStrategy);

情况五:通过应用沙箱中的m3u8文件播放在线流媒体资源

当应用需要通过解析应用沙箱中的m3u8文件,播放在线流媒体资源时,可以通过fileIo.openSync获取文件句柄,将其拼接成fdUrl,并通过setMimeType设置MIME类型为APPLICATION_M3U8。

import{media}from'@kit.MediaKit';import{fileIo}from'@kit.CoreFileKit';import{common}from'@kit.AbilityKit';// 类成员定义avPlayer和context。privateavPlayer:media.AVPlayer|null=null;privatecontext:common.UIAbilityContext|undefined=undefined;privatem3u8FileName:string='';// 在业务函数中(示例工程函数名为avSetupURL):// 创建avPlayer实例对象。this.avPlayer=awaitmedia.createAVPlayer();this.context=this.getUIContext().getHostContext()ascommon.UIAbilityContext;// 通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例。letm3u8FileName='';letfilePath=`${this.context.filesDir}/${m3u8FileName}`;// 通过fileIo.openSync获取文件句柄。letfile=fileIo.openSync(filePath,fileIo.OpenMode.READ_ONLY);letfd:string=file.fd.toString();// 用文件句柄构造本地m3u8的URL。letfdUrl:string="fd://"+fd+"?offset="+"0"+"&size="+"0";// 按需设置HTTP请求头。letheaders:Record<string,string>={"User-Agent":"User-Agent-Value","Cookie":"Cookie-Value"};// 通过本地m3u8的URL和HTTP请求头构造mediaSource媒体来源。letmediaSource:media.MediaSource=media.createMediaSourceWithUrl(fdUrl,headers);// 设置媒体MIME类型为APPLICATION_M3U8。letmimeType:media.AVMimeTypes=media.AVMimeTypes.APPLICATION_M3U8;mediaSource?.setMimeType(mimeType);// 设置播放策略,设置缓冲区数据量为20s。letplaybackStrategy:media.PlaybackStrategy={preferredBufferDuration:20};// 为avPlayer设置媒体来源和播放策略。this.avPlayer.setMediaSource(mediaSource,playbackStrategy);

本地raw文件播放场景下设置URL

情况一:应用沙箱文件播放

import{media}from'@kit.MediaKit';import{fileIo}from'@kit.CoreFileKit';import{common}from'@kit.AbilityKit';// 类成员定义avPlayer,context和fileName。privateavPlayer:media.AVPlayer|null=null;privatecontext:common.UIAbilityContext|undefined=undefined;privatefileName:string='';// 在业务函数中(示例工程函数名为avSetupURL):// 创建avPlayer实例对象。this.avPlayer=awaitmedia.createAVPlayer();this.context=this.getUIContext().getHostContext()ascommon.UIAbilityContext;letfdPath='fd://';letfileName='test.mp4';// test.mp4为应用文件目录下的预置资源,需要开发者根据实际情况进行替换。// 通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例。letpath=`${this.context?.filesDir}/${this.fileName}`;// 打开相应的资源文件地址获取fd,并为url赋值触发initialized状态机上报。letfile=awaitfileIo.open(path);fdPath=fdPath+''+file.fd;this.avPlayer.url=fdPath;

情况二:本地文件播放

说明:
当使用AVPlayer播放本地资源时,AVPlayer会独占此fd。

import{media}from'@kit.MediaKit';import{common}from'@kit.AbilityKit';// 类成员定义avPlayer,context和fileName。privateavPlayer:media.AVPlayer|null=null;privatefileName:string='';privatecontext:common.UIAbilityContext|undefined=undefined;// 在业务函数中(示例工程函数名为avSetupURL):// 创建avPlayer实例对象。this.avPlayer=awaitmedia.createAVPlayer();this.context=this.getUIContext().getHostContext()ascommon.UIAbilityContext;// 通过UIAbilityContext的resourceManager成员的getRawFd接口获取媒体资源播放地址。// 返回类型为{fd,offset,length},fd为HAP包fd地址,offset为媒体资源偏移量,length为播放长度。letfileName='test.mp4';// test.mp4为应用文件目录下的预置资源,需要开发者根据实际情况进行替换。letfileDescriptor=awaitthis.context?.resourceManager.getRawFd(this.fileName);letavFileDescriptor:media.AVFileDescriptor={fd:fileDescriptor.fd,offset:fileDescriptor.offset,length:fileDescriptor.length};// 为fdSrc赋值触发initialized状态机上报。this.avPlayer.fdSrc=avFileDescriptor;

运行完整示例

  1. 新建工程,下载示例工程(也可直接运行),并将示例工程的以下资源复制到对应目录。

    AVPlayerArkTSURL entry/src/main/ets/ └── pages └── Index.ets (播放界面) entry/src/main/resources/ ├── base │ ├── element │ │ ├── color.json │ │ ├── float.json │ │ └── string.json │ └── media │ ├── ic_video_play.svg (播放键图片资源) │ └── ic_video_pause.svg (暂停键图片资源) └── rawfile ├── test.m3u8 (m3u8资源) └── test_01.mp3 (音频资源)
  2. 在/entry/src/main/module.json5中,申请使用网络的权限(或直接替换为示例工程的module.json5)。

    "requestPermissions":[{"name":"ohos.permission.INTERNET"},{"name":"ohos.permission.GET_WIFI_INFO"}]
  3. 通过注释、解注释/entry/src/main/ets/pages/Index.ets中的上文示例的各种情况,编译并运行。

  4. 在安装应用后,可将示例工程的/entry/src/main/resources/rawfile/test.m3u8通过以下命令加入应用沙箱,从而运行应用沙箱相关示例:(<FILESDIR>为物理路径,以示例工程为例,可通过console.info打印"this.context.filesDir"得到应用沙箱路径,再根据应用沙箱指南的应用沙箱路径和真实物理路径的对应关系表找到物理路径)。

    hdc file send "[目录]\test.m3u8" <FILESDIR> hdc file send "[目录]\test_01.mp3" <FILESDIR>
http://www.cnnetsun.cn/news/3877344.html

相关文章:

  • X-VLA (LeRobot)预处理器工作原理:图像、状态与语言指令的协同处理
  • 如何的找网站建设公司-避坑指南与实战攻略,助你找到最靠谱的合作伙伴
  • 构建低消耗的产研AI工作流:Workbuddy生态 + 墨刀AI 落地实践
  • WPGraphQL for WooCommerce安全最佳实践:JWT认证与会话管理
  • 数字沙盘服务商对比:2026年主流厂商能力拆解与选型指南
  • 如何打造高转化网站专题建设方案:从底层逻辑到视觉落地的全实战指南
  • 在线面试准备指南:设备调试与环境布置全解析
  • 笔记二十一:Agentic RL 从入门到精通——训练能自己动手干活的 AI 智能体
  • 科研采购进入“合规协同”阶段——为什么管理型采购平台比单纯电商入口更值得关注
  • Elixir-Slack:构建实时Slack机器人的终极指南
  • 揭秘一等一网站建设背后的匠心独运与流量密码
  • MySQL数据库空间监控与优化实战指南
  • MIPI CSI-2相机接口深度解析:D-PHY/C-PHY物理层、Lane带宽计算与嵌入式机器人视觉应用实践
  • WorkBuddy智能工作台配置优化指南:从环境依赖到自定义指令的完整调优
  • 广东网站建设方便?揭秘那些让您省时省力的隐形逻辑,老板们别再踩坑了
  • 实测VoiceBench榜首模型:NVIDIA NemotronLabs VoiceChat-11B对话流畅度与响应速度评测
  • 网站建设项目方案怎么避坑?资深项目经理揭秘从0到1的高质量落地指南,帮你省钱又省心
  • Docker Compose实战:从零编排Spring Boot+Nginx+MySQL微服务应用
  • xECG_base_model_v1高级应用:少导联ECG信号处理与零填充技术实践
  • 商标设计注册取名用了常用词,怎么补救?
  • Loop for Mac终极指南:如何用优雅的窗口管理工具提升300%工作效率
  • UE5蓝图教程:从零构建可拖拽道具栏系统,实现UI与游戏世界交互
  • ScaffDiff训练秘籍:45分钟混合支架微调实现部署级性能
  • Tk-Instruct-small-def-pos核心功能揭秘:1600+NLP任务的通用解决方案
  • 云服务器部署MeterSphere全攻略:从Docker到生产环境
  • Unity游戏AI开发:使用NPBehave行为树构建智能敌人追逐系统
  • 消费者调查这件事,交给专业团队做更靠谱
  • 西宁网站建设排名:本地企业如何通过实战避坑打造高转化率官网
  • Linux consoletype 命令详解:一键判断物理终端 / 伪终端类型
  • Graph of Thoughts实战:KRAGEN如何将复杂问题拆解为可视化思维图谱