Bootstrap

AvPlayer

//1导入media模块
import { media } from ‘@kit.MediaKit’;
import common from ‘@ohos.app.ability.common’;

@Entry
@Component
struct Index {
avPlayer: media.AVPlayer = null!

build() {

Column() {
  Button('设置播放源').onClick(
    async () => {
      //2.createAVPlayer
      this.avPlayer = await media.createAVPlayer()

     //3.监听状态机
      this.avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => {
        switch (state) {
          case 'idle': // 成功调用reset接口后触发该状态机上报
            console.info('AVPlayer state idle called.');
            break;
          case 'initialized': // avplayer 设置播放源后触发该状态上报
            console.info('AVPlayer state initialized called.');
            this.avPlayer.prepare();
            break;
          case 'prepared': // prepare调用成功后上报该状态机
            console.info('AVPlayer state prepared called.');
            break;
          case 'playing': // play成功调用后触发该状态机上报
            console.info('AVPlayer state playing called.');
            break;
          case 'paused': // pause成功调用后触发该状态机上报
            console.info('AVPlayer state paused called.');
            break;
          case 'completed': // 播放结束后触发该状态机上报
            console.info('AVPlayer state completed called.');
            this.avPlayer.stop(); //调用播放结束接口
            break;
          case 'stopped': // stop接口成功调用后触发该状态机上报
            console.info('AVPlayer state stopped called.');
            this.avPlayer.release(); // 调用reset接口初始化avplayer状态
            break;
          case 'released':
            console.info('AVPlayer state released called.');
            break;
          default:
            console.info('AVPlayer state unknown called.');
            break;
        }
      })
      //error回调监听函数
      this.avPlayer.on('error', (err) => {
        console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`);
        this.avPlayer.reset(); // 调用reset重置资源,触发idle状态
      })

      //以下demo为使用资源管理接口获取打包在HAP内的媒体资源文件并通过fdSrc属性进行播放示例
      // 通过UIAbilityContext的resourceManager成员的getRawFd接口获取媒体资源播放地址
      let context = getContext(this) as common.UIAbilityContext;
      let fileDescriptor = await context.resourceManager.getRawFd('3.m4a');
      let avFileDescriptor: media.AVFileDescriptor =
        { fd: fileDescriptor.fd, offset: fileDescriptor.offset, length: fileDescriptor.length };

      // 为fdSrc赋值本地播放源
      this.avPlayer.fdSrc = avFileDescriptor;
      //在线播放源
      // this.avPlayer.url = 'http://yjy-teach-oss.oss-cn-beijing.aliyuncs.com/HeimaCloudMusic/3.m4a'
    })
  Button('PLAY').onClick(() => {
    this.avPlayer.play()
  })
  Button('PAUSE').onClick(() => {
    this.avPlayer.pause()
  })

}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.SpaceEvenly)

}
}

;