制作一个OpenHarmony视频播放器

简介

媒体子系统是 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 接口


导入模块

import media from '@ohos.multimedia.media';` 
  • 创建 avplayer
this.avPlayer = await media.createAVPlayer()` 

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

/**
  * Creates an AVPlayer instance.
  * @since 9
  * @syscap SystemCapability.Multimedia.Media.AVPlayer
  * @param callback Callback used to return AVPlayer instance if the operation is successful; returns null otherwise.
  * @throws { BusinessError } 5400101 - No memory. Return by callback.
  */
  function createAVPlayer(callback: AsyncCallback<AVPlayer>): void;

 /**
  * Creates an AVPlayer instance.
  * @since 9
  * @syscap SystemCapability.Multimedia.Media.AVPlayer
  * @returns A Promise instance used to return AVPlayer instance if the operation is successful; returns null otherwise.
  * @throws { BusinessError } 5400101 - No memory. Return by promise.
  */
  function createAVPlayer() : Promise<AVPlayer>;` 

*   注册 avplayer 回调
   
   `//注册状态变化回调,不同状态时做不同动作
   avPlayer.on('stateChange', async (state, reason) => {
       ……
   })
   //注册时间变化回调,方便更新进度条时间
   avPlayer.on('timeUpdate', (time:number) => {
       ……
   })
  • avplayer 播放流程
//视频播放伪代码
async avPlayerDemo() {
    this.avPlayer.on('stateChange', async (state, reason) => {
        switch (state) {
            case 'idle': // 成功调用reset接口后触发该状态机上报
                console.info(TAG + 'state idle called')
                this.avPlayer.release() // 释放avplayer对象
                break;
            case 'initialized': // avplayer 设置播放源后触发该状态上报
                console.info(TAG + 'state initialized called ')
                this.avPlayer.surfaceId = this.surfaceID // 设置显示画面,当播放的资源为纯音频时无需设置
                this.avPlayer.prepare().then(() => {
                    console.info(TAG+ 'prepare success');
                }, (err) => {
                    console.error(TAG + 'prepare filed,error message is :' + err.message)
                })
                break;
            case 'prepared': // prepare调用成功后上报该状态机
                console.info(TAG + 'state prepared called')
                this.avPlayer.play() // 调用播放接口开始播放
                break;
            case 'playing': // play成功调用后触发该状态机上报
                console.info(TAG + 'state playing called')
                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 + 'state paused called')
                if (this.count == 0) {
                    this.count++
                    this.avPlayer.play() // 继续调用播放接口开始播放
                }
                break;
            case 'completed': // 播放结束后触发该状态机上报
                console.info(TAG + 'state completed called')
                this.avPlayer.stop() //调用播放结束接口
                break;
            case 'stopped': // stop接口成功调用后触发该状态机上报
                console.info(TAG + 'state stopped called')
                this.avPlayer.reset() // 调用reset接口初始化avplayer状态
                break;
            case 'released':
                console.info(TAG + 'state released called')
                break;
            case 'error':
                console.info(TAG + 'state error called')
                break;
            default:
                console.info(TAG + 'unkown state :' + state)
                break;
        }
    })

    // 创建avPlayer实例对象
    this.avPlayer = await media.createAVPlayer()
    let fdPath = 'fd://'
    let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。
    // path路径的码流可通过"hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" 命令,将其推送到设备上
    let path = pathDir  + '/H264_AAC.mp4'
    let file = await fs.open(path)
    fdPath = fdPath + '' + file.fd
    //赋值url后就会进入stateChange callback
    this.avPlayer.url = fdPath
}
  • 其他播放控制接口
          /**
         * Prepare audio/video playback, it will request resource for playing.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param callback A callback instance used to return when prepare completed.
         * @throws { BusinessError } 5400102 - Operation not allowed. Return by callback.
         * @throws { BusinessError } 5400106 - Unsupport format. Return by callback.
         */
        prepare(callback: AsyncCallback<void>): void;
    
        /**
         * Prepare audio/video playback, it will request resource for playing.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @returns A Promise instance used to return when prepare completed.
         * @throws { BusinessError } 5400102 - Operation not allowed. Return by promise.
         * @throws { BusinessError } 5400106 - Unsupport format. Return by promise.
         */
        prepare(): Promise<void>;
    
        /**
         * Play audio/video playback.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param callback A callback instance used to return when play completed.
         * @throws { BusinessError } 5400102 - Operation not allowed. Return by callback.
         */
        play(callback: AsyncCallback<void>): void;
    
        /**
         * Play audio/video playback.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @returns A Promise instance used to return when play completed.
         * @throws { BusinessError } 5400102 - Operation not allowed. Return by promise.
         */
        play(): Promise<void>;
    
        /**
         * Pause audio/video playback.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param callback A callback instance used to return when pause completed.
         * @throws { BusinessError } 5400102 - Operation not allowed. Return by callback.
         */
        pause(callback: AsyncCallback<void>): void;
    
        /**
         * Pause audio/video playback.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @returns A Promise instance used to return when pause completed.
         * @throws { BusinessError } 5400102 - Operation not allowed. Return by promise.
         */
        pause(): Promise<void>;
    
        /**
         * Stop audio/video playback.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param callback A callback instance used to return when stop completed.
         * @throws { BusinessError } 5400102 - Operation not allowed. Return by callback.
         */
        stop(callback: AsyncCallback<void>): void;
    
         /**
          * Stop audio/video playback.
          * @since 9
          * @syscap SystemCapability.Multimedia.Media.AVPlayer
          * @returns A Promise instance used to return when stop completed.
          * @throws { BusinessError } 5400102 - Operation not allowed. Return by promise.
          */
        stop(): Promise<void>;
    
        /**
         * Reset AVPlayer, it will to idle state and can set src again.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param callback A callback instance used to return when reset completed.
         * @throws { BusinessError } 5400102 - Operation not allowed. Return by callback.
         */
        reset(callback: AsyncCallback<void>): void;
    
        /**
         * Reset AVPlayer, it will to idle state and can set src again.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @returns A Promise instance used to return when reset completed.
         * @throws { BusinessError } 5400102 - Operation not allowed. Return by promise.
         */
        reset(): Promise<void>;
    
        /**
         * Releases resources used for AVPlayer.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param callback A callback instance used to return when release completed.
         * @throws { BusinessError } 5400102 - Operation not allowed. Return by callback.
         */
        release(callback: AsyncCallback<void>): void;
    
        /**
         * Releases resources used for AVPlayer.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @returns A Promise instance used to return when release completed.
         * @throws { BusinessError } 5400102 - Operation not allowed. Return by promise.
         */
        release(): Promise<void>;
    
        /**
         * Jumps to the specified playback position.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param timeMs Playback position to jump, should be in [0, duration].
         * @param mode See @SeekMode .
         */
        seek(timeMs: number, mode?:SeekMode): void;` 
  • 其他回调接口
          /**
         * Register or unregister listens for media playback events.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback stateChange event.
         */
        on(type: 'stateChange', callback: (state: AVPlayerState, reason: StateChangeReason) => void): void;
        off(type: 'stateChange'): void;
        /**
         * Register or unregister listens for media playback events.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback volume event.
         */
        on(type: 'volumeChange', callback: Callback<number>): void;
        off(type: 'volumeChange'): void;
        /**
         * Register or unregister listens for media playback events.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback end of stream
         */
        on(type: 'endOfStream', callback: Callback<void>): void;
        off(type: 'endOfStream'): void;
        /**
         * Register or unregister listens for media playback events.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback seekDone event.
         */
        on(type: 'seekDone', callback: Callback<number>): void;
        off(type: 'seekDone'): void;
        /**
         * Register or unregister listens for media playback events.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback speedDone event.
         */
        on(type: 'speedDone', callback: Callback<number>): void;
        off(type: 'speedDone'): void;
        /**
         * Register or unregister listens for media playback events.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback setBitrateDone event.
         */
        on(type: 'bitrateDone', callback: Callback<number>): void;
        off(type: 'bitrateDone'): void;
        /**
         * LRegister or unregister listens for media playback events.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback timeUpdate event.
         */
        on(type: 'timeUpdate', callback: Callback<number>): void;
        off(type: 'timeUpdate'): void;
        /**
         * Register or unregister listens for media playback events.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback durationUpdate event.
         */
        on(type: 'durationUpdate', callback: Callback<number>): void;
        off(type: 'durationUpdate'): void;
        /**
         * Register or unregister listens for video playback buffering events.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback buffering update event to listen for.
         * @param callback Callback used to listen for the buffering update event, return BufferingInfoType and the value.
         */
        on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void;
        off(type: 'bufferingUpdate'): void;
        /**
         * Register or unregister listens for start render video frame events.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback event return .
         */
        on(type: 'startRenderFrame', callback: Callback<void>): void;
        off(type: 'startRenderFrame'): void;
        /**
         * Register or unregister listens for video size change event.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback event return video size.
         */
        on(type: 'videoSizeChange', callback: (width: number, height: number) => void): void;
        off(type: 'videoSizeChange'): void;
        /**
         * Register or unregister listens for audio interrupt event, refer to {@link #audio.InterruptEvent}
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback event return audio interrupt info.
         */
        on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void;
        off(type: 'audioInterrupt'): void;
        /**
         * Register or unregister listens for available bitrate list collect completed events for HLS protocol stream playback.
         * This event will be reported after the {@link #prepare} called.
         * @since 9
         * @syscap SystemCapability.Multimedia.Media.AVPlayer
         * @param type Type of the playback event to listen for.
         * @param callback Callback used to listen for the playback event return available bitrate list.
         */
        on(type: 'availableBitrates', callback: (bitrates: Array<number>) => 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, 'seek time change')
                 this.currentTime = this.fileAsset.duration * value / 100
                 this.videoPlayer.seek(this.currentTime)
               })
           }
           .height('100%')
           .zIndex(2)
         }
         Row() {
           XComponent({
             id: 'componentId',
             type: 'surface',
             controller: this.mxcomponentController
           })
             .onLoad(() => {
               Logger.info(TAG, 'onLoad is called')
               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/Videos
      async prepareVideo() {
        this.ratio = this.fileAsset.width / this.fileAsset.height
        this.mxcomponentController.setXComponentsurfaceSize({
          surfaceWidth: this.fileAsset.width,
          surfaceHeight: this.fileAsset.height
        })
        this.surfaceId = this.mxcomponentController.getXComponentsurfaceId()
        this.fd = await this.fileAsset.open('Rw')
        Logger.info(TAG, `fd://' ${this.fd} `)
        return 'fd://' + this.fd
      }
      //初始化视频文件并初始化avplayer
      async playVideo() {
        Logger.info(TAG, 'playVideo')
        try{
          await this.getMediaList()
          let fdPath = await this.prepareVideo()
          this.videoPlayer.on('timeUpdate', (time:number) => {
            console.info('timeUpdate success,and new time is :' + time)
            this.currentTime = time;
          })
          await this.videoPlayer.initVideoPlayer(fdPath, this.surfaceId)
          this.isPlaying = true
        }catch(error) {
          Logger.info(TAG, `playVideo error ${JSON.stringify(error)}`)
        }
      }

写在最后

如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙

  • 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
  • 关注小编,同时可以期待后续文章ing🚀,不定期分享原创知识。
  • 想要获取更多完整鸿蒙最新学习知识点,请移步前往小编:https://gitee.com/MNxiaona/733GH/blob/master/jianshu
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,839评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,543评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,116评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,371评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,384评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,111评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,416评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,053评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,558评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,007评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,117评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,756评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,324评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,315评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,539评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,578评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,877评论 2 345

推荐阅读更多精彩内容