您的当前位置:首页>新闻 > 正文

世界微头条丨鸿蒙上制作一个视频播放器

  • 2023-04-11 11:05:18 来源:OST开源开发者

媒体子系统是 OpenHarmony中重要的子系统,可以提供音视频播放能力。

媒体子系统为开发者提供一套简单且易于理解的接口,使得开发者能够方便接入系统并使用系统的媒体资源。


【资料图】

媒体子系统提供以下常用功能如下:

①音视频播放(AVPlayer9+),AudioPlayer6+ 和 VideoPlayer8+ 整合,升级了状态机和错误码,推荐使用。

②音视频录制(AVRecorder9+),AudioRecorder6+ 和 VideoRecorder9+ 整合,推荐使用。

③音频播放(AudioPlayer6+),AVPlayer9+ 发布后停止维护,请使用 AVPlayer9+。

视频播放(VideoPlayer8+),AVPlayer9+ 发布后停止维护,请使用 AVPlayer9+。

⑤音频录制(AudioRecorder6+),AVRecorder9+ 发布后停止维护,请使用 AVRecorder9+。

⑥视频录制(VideoRecorder9+),AVRecorder9+ 发布后停止维护,请使用 AVRecorder9+。

从 3.2 开始 OpenHarmony 推出了 AVPlayer 和 AVRecorder 接口,之前的 VideoPlayer、AudioPlayer 这些接口会停止维护,所以我们今天学习下怎么使用 AVPlayer 接口。

导入模块

importmediafrom"@ohos.multimedia.media";

创建 avplayer:

this.avPlayer=awaitmedia.createAVPlayer()

如上,我们使用的是 promise 接口,对应的接口定义为:

/***CreatesanAVPlayerinstance.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramcallbackCallbackusedtoreturnAVPlayerinstanceiftheoperationissuccessful;returnsnullotherwise.*@throws{BusinessError}5400101-Nomemory.Returnbycallback.*/functioncreateAVPlayer(callback:AsyncCallback):void;/***CreatesanAVPlayerinstance.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@returnsAPromiseinstanceusedtoreturnAVPlayerinstanceiftheoperationissuccessful;returnsnullotherwise.*@throws{BusinessError}5400101-Nomemory.Returnbypromise.*/functioncreateAVPlayer():Promise;
注册 avplayer 回调:
//注册状态变化回调,不同状态时做不同动作avPlayer.on("stateChange",async(state,reason)=>{……})//注册时间变化回调,方便更新进度条时间avPlayer.on("timeUpdate",(time:number)=>{……})
avplayer 播放流程:
graphLR赋值avPlayer.url开始播放-->回调进入initialized-->赋值avPlayer.surfaceId-->avPlayer.prepare-->回调进入prepared-->avPlayer.play
//视频播放伪代码asyncavPlayerDemo(){this.avPlayer.on("stateChange",async(state,reason)=>{switch(state){case"idle"://成功调用reset接口后触发该状态机上报console.info(TAG+"stateidlecalled")this.avPlayer.release()//释放avplayer对象break;case"initialized"://avplayer设置播放源后触发该状态上报console.info(TAG+"stateinitializedcalled")this.avPlayer.surfaceId=this.surfaceID//设置显示画面,当播放的资源为纯音频时无需设置this.avPlayer.prepare().then(()=>{console.info(TAG+"preparesuccess");},(err)=>{console.error(TAG+"preparefiled,errormessageis:"+err.message)})break;case"prepared"://prepare调用成功后上报该状态机console.info(TAG+"statepreparedcalled")this.avPlayer.play()//调用播放接口开始播放break;case"playing"://play成功调用后触发该状态机上报console.info(TAG+"stateplayingcalled")if(this.count==0){this.avPlayer.pause()//调用暂停播放接口}else{this.avPlayer.seek(10000,media.SeekMode.SEEK_PREV_SYNC)//前向seek置10秒处,触发seekDone回调函数}break;case"paused"://pause成功调用后触发该状态机上报console.info(TAG+"statepausedcalled")if(this.count==0){this.count++this.avPlayer.play()//继续调用播放接口开始播放}break;case"completed"://播放结束后触发该状态机上报console.info(TAG+"statecompletedcalled")this.avPlayer.stop()//调用播放结束接口break;case"stopped"://stop接口成功调用后触发该状态机上报console.info(TAG+"statestoppedcalled")this.avPlayer.reset()//调用reset接口初始化avplayer状态break;case"released":console.info(TAG+"statereleasedcalled")break;case"error":console.info(TAG+"stateerrorcalled")break;default:console.info(TAG+"unkownstate:"+state)break;}})//创建avPlayer实例对象this.avPlayer=awaitmedia.createAVPlayer()letfdPath="fd://"letpathDir="/data/storage/el2/base/haps/entry/files"//pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。//path路径的码流可通过"hdcfilesendD:xxxH264_AAC.mp4/data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files"命令,将其推送到设备上letpath=pathDir+"/H264_AAC.mp4"letfile=awaitfs.open(path)fdPath=fdPath+""+file.fd//赋值url后就会进入stateChangecallbackthis.avPlayer.url=fdPath}
其他播放控制接口:
/***Prepareaudio/videoplayback,itwillrequestresourceforplaying.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramcallbackAcallbackinstanceusedtoreturnwhenpreparecompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbycallback.*@throws{BusinessError}5400106-Unsupportformat.Returnbycallback.*/prepare(callback:AsyncCallback):void;/***Prepareaudio/videoplayback,itwillrequestresourceforplaying.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@returnsAPromiseinstanceusedtoreturnwhenpreparecompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbypromise.*@throws{BusinessError}5400106-Unsupportformat.Returnbypromise.*/prepare():Promise;/***Playaudio/videoplayback.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramcallbackAcallbackinstanceusedtoreturnwhenplaycompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbycallback.*/play(callback:AsyncCallback):void;/***Playaudio/videoplayback.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@returnsAPromiseinstanceusedtoreturnwhenplaycompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbypromise.*/play():Promise;/***Pauseaudio/videoplayback.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramcallbackAcallbackinstanceusedtoreturnwhenpausecompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbycallback.*/pause(callback:AsyncCallback):void;/***Pauseaudio/videoplayback.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@returnsAPromiseinstanceusedtoreturnwhenpausecompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbypromise.*/pause():Promise;/***Stopaudio/videoplayback.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramcallbackAcallbackinstanceusedtoreturnwhenstopcompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbycallback.*/stop(callback:AsyncCallback):void;/***Stopaudio/videoplayback.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@returnsAPromiseinstanceusedtoreturnwhenstopcompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbypromise.*/stop():Promise;/***ResetAVPlayer,itwilltoidlestateandcansetsrcagain.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramcallbackAcallbackinstanceusedtoreturnwhenresetcompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbycallback.*/reset(callback:AsyncCallback):void;/***ResetAVPlayer,itwilltoidlestateandcansetsrcagain.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@returnsAPromiseinstanceusedtoreturnwhenresetcompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbypromise.*/reset():Promise;/***ReleasesresourcesusedforAVPlayer.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramcallbackAcallbackinstanceusedtoreturnwhenreleasecompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbycallback.*/release(callback:AsyncCallback):void;/***ReleasesresourcesusedforAVPlayer.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@returnsAPromiseinstanceusedtoreturnwhenreleasecompleted.*@throws{BusinessError}5400102-Operationnotallowed.Returnbypromise.*/release():Promise;/***Jumpstothespecifiedplaybackposition.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtimeMsPlaybackpositiontojump,shouldbein[0,duration].*@parammodeSee@SeekMode.*/seek(timeMs:number,mode?void;
其他回调接口:
/***Registerorunregisterlistensformediaplaybackevents.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybackstateChangeevent.*/on(type:"stateChange",callback:(state:AVPlayerState,reason:StateChangeReason)=>void):void;off(type:"stateChange"):void;/***Registerorunregisterlistensformediaplaybackevents.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybackvolumeevent.*/on(type:"volumeChange",callback:Callback):void;off(type:"volumeChange"):void;/***Registerorunregisterlistensformediaplaybackevents.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybackendofstream*/on(type:"endOfStream",callback:Callback):void;off(type:"endOfStream"):void;/***Registerorunregisterlistensformediaplaybackevents.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybackseekDoneevent.*/on(type:"seekDone",callback:Callback):void;off(type:"seekDone"):void;/***Registerorunregisterlistensformediaplaybackevents.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybackspeedDoneevent.*/on(type:"speedDone",callback:Callback):void;off(type:"speedDone"):void;/***Registerorunregisterlistensformediaplaybackevents.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybacksetBitrateDoneevent.*/on(type:"bitrateDone",callback:Callback):void;off(type:"bitrateDone"):void;/***LRegisterorunregisterlistensformediaplaybackevents.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybacktimeUpdateevent.*/on(type:"timeUpdate",callback:Callback):void;off(type:"timeUpdate"):void;/***Registerorunregisterlistensformediaplaybackevents.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybackdurationUpdateevent.*/on(type:"durationUpdate",callback:Callback):void;off(type:"durationUpdate"):void;/***Registerorunregisterlistensforvideoplaybackbufferingevents.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackbufferingupdateeventtolistenfor.*@paramcallbackCallbackusedtolistenforthebufferingupdateevent,returnBufferingInfoTypeandthevalue.*/on(type:"bufferingUpdate",callback:(infoType:BufferingInfoType,value:number)=>void):void;off(type:"bufferingUpdate"):void;/***Registerorunregisterlistensforstartrendervideoframeevents.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybackeventreturn.*/on(type:"startRenderFrame",callback:Callback):void;off(type:"startRenderFrame"):void;/***Registerorunregisterlistensforvideosizechangeevent.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybackeventreturnvideosize.*/on(type:"videoSizeChange",callback:(width:number,height:number)=>void):void;off(type:"videoSizeChange"):void;/***Registerorunregisterlistensforaudiointerruptevent,referto{@link#audio.InterruptEvent}*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybackeventreturnaudiointerruptinfo.*/on(type:"audioInterrupt",callback:(info:audio.InterruptEvent)=>void):void;off(type:"audioInterrupt"):void;/***RegisterorunregisterlistensforavailablebitratelistcollectcompletedeventsforHLSprotocolstreamplayback.*Thiseventwillbereportedafterthe{@link#prepare}called.*@since9*@syscapSystemCapability.Multimedia.Media.AVPlayer*@paramtypeTypeoftheplaybackeventtolistenfor.*@paramcallbackCallbackusedtolistenfortheplaybackeventreturnavailablebitratelist.*/on(type:"availableBitrates",callback:(bitrates:Array)=>void):void;off(type:"availableBitrates"):void;

简单样例

界面:

build(){Stack({alignContent:Alignment.Center}){if(this.isShowMenu){Column(){//视频名称PlayTitle({title:this.displayName,handleBack:this.handleBack})Row(){//播放控件PreVideo({handleClick:this.handlePrevClick})PlayButton({isPlaying:$isPlaying})NextVideo({handleClick:this.handleNextClick})}.margin({top:"40%"})Blank()//时间刻度Row(){Text(getTimeString(this.currentTime)).fontSize(25).fontColor(Color.White)Blank()Text(this.fileAsset?getTimeString(this.fileAsset.duration):"00:00").fontSize(25).fontColor(Color.White)}.width("95%")//进度条Slider({value:this.fileAsset?this.currentTime/this.fileAsset.duration*100:0}).width("92%").selectedColor(Color.White).onChange((value:number)=>{Logger.info(TAG,"seektimechange")this.currentTime=this.fileAsset.duration*value/100this.videoPlayer.seek(this.currentTime)})}.height("100%").zIndex(2)}Row(){XComponent({id:"componentId",type:"surface",controller:this.mxcomponentController}).onLoad(()=>{Logger.info(TAG,"onLoadiscalled")this.playVideo()}).width("100%").aspectRatio(this.ratio)}.height("100%").width("100%").justifyContent(FlexAlign.Center)}.width("100%").height("100%").backgroundColor(Color.Black).onClick(()=>{this.isShowMenu=!this.isShowMenu})}
播放:
//根据视频文件获取视频源尺寸并生成surface//视频文件的路径在/storage/media/100/local/files/VideosasyncprepareVideo(){this.ratio=this.fileAsset.width/this.fileAsset.heightthis.mxcomponentController.setXComponentsurfaceSize({surfaceWidth:this.fileAsset.width,surfaceHeight:this.fileAsset.height})this.surfaceId=this.mxcomponentController.getXComponentsurfaceId()this.fd=awaitthis.fileAsset.open("Rw")Logger.info(TAG,`fd://"${this.fd}`)return"fd://"+this.fd}//初始化视频文件并初始化avplayerasyncplayVideo(){Logger.info(TAG,"playVideo")try{awaitthis.getMediaList()letfdPath=awaitthis.prepareVideo()this.videoPlayer.on("timeUpdate",(time:number)=>{console.info("timeUpdatesuccess,andnewtimeis:"+time)this.currentTime=time;})awaitthis.videoPlayer.initVideoPlayer(fdPath,this.surfaceId)this.isPlaying=true}catch(error){Logger.info(TAG,`playVideoerror${JSON.stringify(error)}`)}}

小结

参考链接:

https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-media.md#play9

审核编辑:汤梓红

标签:

推荐阅读

世界微头条丨鸿蒙上制作一个视频播放器

媒体子系统是OpenHarmony中重要的子系统,可以提供音视频播放能力。

2023中铁工程装备集团技术服务有限公司公开招聘

2023中铁工程装备集团技术服务有限公司公开招聘一、公司简介中铁工程装备集团技术服务有限公司成立于201...

【天天聚看点】让专利供给和市场需求握手(人民时评)

现代快报网是由凤凰出版传媒集团旗下的现代快报倾力打造的江苏新闻门户网站,目前在南京、苏州、无锡、常...

全球今日讯!黑海惊魂!美军方泄密文件显示:去年9月俄军差点击落英侦察机

【任重环球时报记者马俊】此次泄密的美国军方文件显示,俄罗斯战斗机曾在黑海上空差点击落一架英国侦察...

【全球时快讯】比亚迪f0

1、比亚迪F0是比亚迪公司推出的一款小排量轿车。2、比亚迪F0外观时尚,搭载比亚迪自主研发的BYD371QA高...

猜您喜欢

【版权及免责声明】凡注明"转载来源"的作品,均转载自其它媒体,转载目的在于传递更多的信息,并不代表本网赞同其观点和对其真实性负责。亚洲经营网倡导尊重与保护知识产权,如发现本站文章存在内容、版权或其它问题,烦请联系。 联系方式:8 86 239 5@qq.com,我们将及时沟通与处理。

公司