HarmonyOS 使用XComponent和AvPlayer播放视频出现有声音无画面问题

参考代码:

Row() {
  XComponent({ id: 'xcomponent', type: XComponentType.SURFACE, controller: this.xcomponentController })
    .onLoad(() => {
      this.surfaceID = this.xcomponentController.getXComponentSurfaceId()
      Logger.info(TAG, "surfaceId=" + this.surfaceID);
      this.xComponentContext = this.xcomponentController.getXComponentContext() as Record<string, () => void>
      let surfaceRect: SurfaceRect = { offsetX: 0, offsetY: 0, surfaceWidth: 500, surfaceHeight: 500 }
      this.xcomponentController.setXComponentSurfaceRect(surfaceRect)
      this.rect = this.xcomponentController.getXComponentSurfaceRect()
    }).width('100%')
    .height(260)
}
.width("95%").backgroundColor("#12638bc1").border({ width: 1, color: Color.Pink })
.justifyContent(FlexAlign.Center)
@Component
export struct VideoControls {
  private context = getContext(this) as common.UIAbilityContext
  @Consume('previewObject') item: fileItem
  @Link avPlayer: media.AVPlayer | undefined;
  @Consume  surfaceID: string;
  // 视频播放倍速
  @Consume currentProgressRate: number
  // SR开关
  @Consume srSwitch: boolean
  // 是否横屏播放
  @StorageLink(AppConfig.isLandscape) isLandscape: boolean = AppStorage.get(AppConfig.isLandscape) || false
  @State count: number = 0;
  @State durationTime: number = 0;

  build() {
    Flex({
      justifyContent: FlexAlign.SpaceBetween,
      alignItems: ItemAlign.Center,
    }) {
      // 播放按钮
      Image(this.item.play ? $r('app.media.icon_pause_white') : $r('app.media.icon_play'))
        .width(px2vp(54))
        .height(px2vp(54))
        .objectFit(ImageFit.Contain)
        .onClick(() => {
          this.iconOnclick();
        })

      // 进度条
      Text(this.item.currentStringTime)
        .fontSize(px2fp(40))
        .fontColor('#BFBFBF')
      Slider({
        value: this.count,
        min: 0,
        max: this.durationTime,
        step: 1,
        style: SliderStyle.OutSet
      })
        .blockColor('#ffffff')
        .width('46.7%')
        .trackColor(Color.Gray)
        .selectedColor('#ffffff')
        .showSteps(true)
        .showTips(true)
        .trackThickness(4)
        .onChange((value: number) => {
          this.sliderOnchange(value);
        })
      Text(this.durationTime.toString())
        .fontSize(px2fp(40))
        .fontColor('#BFBFBF')

      if (!this.isLandscape) {
        Image($r('app.media.icon_fullscreen'))
          .width(px2vp(100))
          .height(px2vp(100))
          .objectFit(ImageFit.Contain)
          .onClick(() => {
            this.isLandscape = true
          })
      }
    }
    .height(px2vp(107.5))
    .padding({
      left: px2vp(13.4),
      right: px2vp(13.4),
    })
  }

  /**
   * 初始化 AvPlayer
   */
  private initAvPlayer(surfaceId: string) {
    Logger.info(TAG, `x compoent surface id=${this.surfaceID}`)
    media.createAVPlayer().then((player) => {
      this.avPlayer = player;
      this.setAVPlayerCallback(this.avPlayer)
      const origin_path: Resource = this.item.path as Resource;
      let video_path: string = ""
      if (origin_path.params != undefined) {
        video_path = origin_path.params[0] as string;
      }
      Logger.info(TAG, `video_path: ${video_path}`)
      this.context.resourceManager.getRawFd(video_path)
        .then((file) => {
          let avFileDescriptor: media.AVFileDescriptor =
            { fd: file.fd, offset: file.offset, length: file.length };
          if (this.avPlayer != undefined) {
            this.avPlayer.fdSrc = avFileDescriptor;
            this.avPlayer.surfaceId = surfaceId;
          }
        })
    });
  }

  private setAVPlayerCallback(avPlayer: media.AVPlayer) {
    avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => {
      switch (state) {
        case 'initialized': // avplayer 设置播放源后触发该状态上报
          avPlayer.prepare();
          break;
        case 'prepared': // prepare调用成功后上报该状态机
          Logger.info(TAG, 'AVPlayer state prepared called.');
          this.count = 0;
          this.durationTime = avPlayer.duration;
          avPlayer.play(); // 调用播放接口开始播放
          break;
        case "playing":
          this.item.play = true;
          this.count += 1 ;
          break;
        case 'completed':
          this.item.play = false;
          break;
        case 'paused':
          this.item.play = false;
          break;
      }
    })
  }

  iconOnclick() {
    if (this.avPlayer == undefined) {
      this.initAvPlayer(this.surfaceID)
    } else {
      if (this.item.play === true) {
        this.item.controller?.pause()
        this.avPlayer?.pause();
        this.item.play = false;
        return;
      } else {
        this.item.controller?.start();
        this.avPlayer?.play((err) => {
          if (err == null) {
            Logger.info(TAG, ' play success');
          } else {
            console.error(TAG, `video pause error:${err.message}`)
          }
        })
        this.item.play = true;
      }
    }
  }

  sliderOnchange(value: number) {
    this.item.currentTime = Number.parseInt(value.toString());
    if (this.avPlayer != undefined) {
      this.avPlayer.seek(value, media.SeekMode.SEEK_NEXT_SYNC);
    }
    this.item.controller?.setCurrentTime(Number.parseInt(value.toString()), SeekMode.Accurate);
  }
}
HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

surfaceId需要在avPlayer的initialized状态下赋值绑定,请参考:

import { media } from '@kit.MediaKit';
import { BusinessError } from '@kit.BasicServicesKit';
const TAG = 'AVPlayerDemo';

@Entry
@Component
struct AVPlayerDemo {
  @State message: string = '读取本地视频'
  private surfaceId: string = ''; // surfaceId,用于关联XComponent与视频播放器
  private mXComponentController: XComponentController = new XComponentController();
  private avPlayer: media.AVPlayer | undefined = undefined;

  aboutToAppear(): void {
    //创建avplayer
    this.initAvPlayer()
  }

  initAvPlayer() {
    media.createAVPlayer().then((avPlayer: media.AVPlayer) => {
      this.avPlayer = avPlayer;
      this.playerCallback(this.avPlayer);

      //加载本地文件
      let fileDescriptor = getContext().resourceManager.getRawFdSync(`video.mp4`);
      let avFileDescriptor: media.AVFileDescriptor = {
        fd: fileDescriptor.fd,
        offset: fileDescriptor.offset,
        length: fileDescriptor.length
      };
      this.avPlayer.fdSrc = avFileDescriptor
    })
  }

  // 注册avplayer回调函数
  playerCallback(avPlayer: media.AVPlayer) {
    avPlayer.on('timeUpdate', (time: number) => {
      console.info(TAG,`AVPlayer timeUpdate. time is ${time}`);
    })
    // error回调监听函数,当avPlayer在操作过程中出现错误时调用 reset接口触发重置流程
    avPlayer.on('error', (err: BusinessError) => {
      console.error(TAG,`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`);
      avPlayer.reset(); // 调用reset重置资源,触发idle状态
    })

    // 状态机变化回调函数
    avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => {
      switch (state) {
        case 'idle': // 成功调用reset接口后触发该状态机上报
          console.info(TAG,'AVPlayer state idle called.');
          break;
        case 'initialized': // avplayer 设置播放源后触发该状态上报
          console.info(TAG,'AVPlayer state initialized called.');
          avPlayer.surfaceId = this.surfaceId;
          avPlayer.prepare();
          break;
        case 'prepared': // prepare调用成功后上报该状态机
          console.info(TAG,'AVPlayer state prepared called.');
          avPlayer.setSpeed(media.PlaybackSpeed.SPEED_FORWARD_1_00_X)
          avPlayer.seek(1, media.SeekMode.SEEK_PREV_SYNC)
        // avPlayer.play();
          break;
        case 'completed': // prepare调用成功后上报该状态机
          console.info(TAG,'AVPlayer state completed called.');
          break;
        case 'playing': // play成功调用后触发该状态机上报
          console.info(TAG,'AVPlayer state playing called.');
          break;
        case 'paused': // pause成功调用后触发该状态机上报
          console.info(TAG,'AVPlayer state paused called.');
          break;
        case 'stopped': // stop接口成功调用后触发该状态机上报
          console.info(TAG,'AVPlayer state stopped called.');
          break;
        case 'released':
          console.info(TAG,'AVPlayer state released called.');
          break;
        default:
          console.info(TAG,'AVPlayer state unknown called.');
          break;
      }
    })
  }

  build() {
    Column({ space: 20 }) {
      XComponent({
        id: 'xComponent',
        type: XComponentType.SURFACE,
        controller: this.mXComponentController
      })
        .onLoad(() => {
          this.mXComponentController.setXComponentSurfaceRect({
            offsetX:0,
            offsetY:0,
            surfaceWidth: 1920,
            surfaceHeight: 1080
          });
          this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
        })
        .width('100%')
        .height('800px')
      Button('播放视频')
        .width(200)
        .height(50)
        .onClick(() => {
          if (this.avPlayer) {
            this.avPlayer.play();
          }
        });
      Button('暂停')
        .width(200)
        .height(50)
        .onClick(() => {
          if (this.avPlayer) {
            this.avPlayer.pause();
          }
        });
    }
    .height('100%')
    .width('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS AvPlayer视频播放速度问题
492浏览 • 1回复 待解决
HarmonyOS XComponent播放视频问题
44浏览 • 1回复 待解决
使用AVPlayer实现视频播放
1331浏览 • 1回复 待解决
AVPlayer实现视频播放
1071浏览 • 1回复 待解决
avplayer播放视频demo
1615浏览 • 1回复 待解决
HarmonyOS 视频播放AVPlayer解码异常
46浏览 • 1回复 待解决
HarmonyOS AVPlayer 播放问题
766浏览 • 1回复 待解决
HarmonyOS AVPlayer XComponent
375浏览 • 1回复 待解决
HarmonyOS soundpool播放声音问题
587浏览 • 1回复 待解决
js采集声音出现问题怎么处理?
3367浏览 • 1回复 待解决