HarmonyOS avplayer音频播放切换播放时,两个音频同时播放,没有清除第一个音频,页面关闭音频还在播放

HarmonyOS
2025-01-10 08:51:05
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
aquaa

参考demo:

import { media } from '@kit.MediaKit';
import { promptAction } from '@kit.ArkUI';
import { window } from '@kit.ArkUI';
import { resourceManager } from '@kit.LocalizationKit';
import { PlayConstants, AvplayerStatus, Events, SliderMode, PlayerModel, VideoItem } from './PlayConstants';
import { GlobalContext } from '../GlobalContext';
import { BusinessError, emitter, systemDateTime } from '@kit.BasicServicesKit';
import avSession from '@ohos.multimedia.avsession';
import { BackGroundUtil } from '../../utils/BackGroundUtil';

@Observed
export class VideoController {
  public playerModel: PlayerModel;
  private avPlayer: media.AVPlayer | null = null;
  private duration: number = 0;
  private status: number = -1;
  private loop: boolean = false;
  private index: number = 0;
  private url?: resourceManager.RawFileDescriptor = {} as resourceManager.RawFileDescriptor;
  private iUrl: string = '';
  private surfaceId: string = '';
  private seekTime: number = PlayConstants.PROGRESS_SEEK_TIME;
  private mAvSession: avSession.AVSession | undefined = undefined;
  private startTime: number = 0;
  private errorTime: number = 0;
  private errorCount: number = 0;

  constructor() {
    this.playerModel = new PlayerModel();
    this.createAVPlayer();
  }

  async createAVPlayer() {
    let avPlayer: media.AVPlayer = await media.createAVPlayer();
    this.avPlayer = avPlayer;
    // this.avPlayer.videoScaleType = media.VideoScaleType.VIDEO_SCALE_TYPE_FIT;
    this.bindState();
    // 初始化 session
    await this.createAvSession("Session", 'video');
    // 申请长时任务
    BackGroundUtil.startContinuousTask();
    // 手动检查 player 状态
    this.checkPlayerHealth();
  }

  async bindState() {
    if (this.avPlayer === null) {
      return;
    }
    this.avPlayer.on(Events.STATE_CHANGE, async (state: media.AVPlayerState) => {
      let avplayerStatus: string = state;
      if (this.avPlayer === null) {
        return;
      }

      console.info("player state is " + state);
      switch (avplayerStatus) {
        case AvplayerStatus.IDLE:
          this.resetProgress();
          if (this.iUrl) {
            this.avPlayer.url = this.iUrl;
          } else {
            this.avPlayer.fdSrc = this.url;
          }
          break;
        case AvplayerStatus.INITIALIZED:
        // this.avPlayer.surfaceId = this.surfaceId;
          this.startTime = systemDateTime.getTime();
          console.info("player start to prepare");
          this.avPlayer.prepare();
          console.info("player prepare ok");
          break;
        case AvplayerStatus.PREPARED:
          console.info("player start to play")
          this.avPlayer.videoScaleType = 0;
          this.setVideoSize();
          this.avPlayer.play();
          this.duration = this.avPlayer.duration;
          this.setMediaMetaInfo("-test", "test", this.duration);
          this.setPlayingState(avSession.PlaybackState.PLAYBACK_STATE_PREPARE);
          console.info(" player play ok")
          break;
        case AvplayerStatus.PLAYING:
          this.avPlayer.setVolume(this.playerModel.volume);
          this.status = PlayConstants.STATUS_START;
          this.setPlayingState(avSession.PlaybackState.PLAYBACK_STATE_PLAY);
          this.watchStatus();
          break;
        case AvplayerStatus.PAUSED:
          this.status = PlayConstants.STATUS_PAUSE;
          this.setPlayingState(avSession.PlaybackState.PLAYBACK_STATE_PAUSE);
          this.watchStatus();
          break;
        case AvplayerStatus.COMPLETED:
          this.playerModel.playSpeed = PlayConstants.PLAY_SPEED;
          this.duration = PlayConstants.PLAYER_DURATION;
          this.setPlayingState(avSession.PlaybackState.PLAYBACK_STATE_STOP);
          console.info("play complete")
          if (!this.loop) {
            let curIndex = this.index + PlayConstants.PLAYER_NEXT;
            let globalVideoList = GlobalContext.getObject("globalVideoList") as VideoItem[];
            this.index = (curIndex === globalVideoList.length) ?
            PlayConstants.PLAYER_FIRST : curIndex;
            if (this.iUrl) {
              this.iUrl = globalVideoList[this.index].iSrc;
            } else {
              this.url = globalVideoList[this.index].src;
            }
          }
          this.avPlayer.reset();
          break;
        case AvplayerStatus.RELEASED:
          this.avPlayer.release();
          this.status = PlayConstants.STATUS_STOP;
          this.watchStatus();
          console.info('[PlayVideoModel] state released called');
          break;
        default:
          console.info('[PlayVideoModel] unKnown state: ' + state);
          break;
      }
    });

    this.avPlayer.on(Events.TIME_UPDATE, (time: number) => {
      this.initProgress(time);
    });
    this.avPlayer.on(Events.ERROR, (error: BusinessError) => {
      this.errorTime = systemDateTime.getTime();
      let dur = this.errorTime - this.startTime;
      console.info("txy player time " + dur);
      this.playError(error);
      // 重试信号
      emitter.emit(PlayConstants.PLAY_ERROR_EVENT);
    })

    this.avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
      console.info('bufferingUpdate called,and infoType value is:' + infoType + ', value is :' + value)
    })

    this.avPlayer.on('availableBitrates', (bitrates: Array<number>) => {
      console.info('availableBitrates called,and availableBitrates length is:' + bitrates.length)
    })
  }

  async firstPlay(index: number, url: resourceManager.RawFileDescriptor, iUrl: string, surfaceId: string) {
    this.index = index;
    this.url = url;
    this.iUrl = iUrl;
    this.surfaceId = surfaceId;
    if (this.avPlayer === null) {
      await this.createAVPlayer();
    }
    if (this.avPlayer !== null) {
      if (this.iUrl) {
        this.avPlayer.url = this.iUrl;
      } else {
        this.avPlayer.fdSrc = this.url;
      }
    }
  }

  // firstPlay with raw file
  async firstPlayWithRawFile(url: resourceManager.RawFileDescriptor, surfaceId: string) {
    this.surfaceId = surfaceId;
    this.url = url;
    if (this.avPlayer === null) {
      await this.createAVPlayer();
    }
    if (this.avPlayer !== null) {
      this.avPlayer.fdSrc = url;
    }
  }

  async playWithRawFile(url: resourceManager.RawFileDescriptor, surfaceId: string) {
    this.surfaceId = surfaceId;
    this.url = url;
  }

  async firstPlayWithUrl(iUrl: string, surfaceId: string) {
    this.surfaceId = surfaceId;
    this.iUrl = iUrl;
    if (this.avPlayer === null) {
      await this.createAVPlayer();
    }
    if (this.avPlayer !== null) {
      this.avPlayer.url = iUrl;
    }
  }

  async firstPlayWithHLS(hlsUrl: string, surfaceId: string) {
    this.surfaceId = surfaceId;
    this.iUrl = hlsUrl;
    if (this.avPlayer === null) {
      await this.createAVPlayer();
    }

    if (this.avPlayer !== null) {
      try {
        let mediaSource : media.MediaSource = media.createMediaSourceWithUrl(hlsUrl);
        let playStrategy : media.PlaybackStrategy = {preferredWidth: 1, preferredHeight: 2, preferredBufferDuration: 3, preferredHdr: false};
        await this.avPlayer?.setMediaSource(mediaSource, playStrategy);
      } catch (e) {
        let err = e as BusinessError;
        console.error("player set hls url is error " + JSON.stringify(err));
      }

    }
  }

  release() {
    if (this.avPlayer !== null) {
      this.avPlayer.release();
    }

    if (this.mAvSession !== null) {
      this.destroyAvSession();
    }

    // 释放长时任务
    BackGroundUtil.stopContinuousTask()
  }

  pause() {
    if (this.avPlayer !== null) {
      this.avPlayer.pause();
    }
  }

  async play() {
    if (this.avPlayer !== null) {
      await this.avPlayer.play();
    }
  }

  async stop() {
    if (this.avPlayer !== null) {
      await this.avPlayer.stop();
    }
  }

  async reset() {
    if (this.avPlayer !== null) {
      console.info("player start reset " + this.avPlayer.state);
      await this.avPlayer.reset();
      console.info("player state is" + this.avPlayer.state);
    }
  }

  async prepare() {
    if (this.avPlayer !== null) {
      this.avPlayer.prepare();
    }
  }

  setLoop() {
    this.loop = !this.loop;
  }

  switchPlayOrPause() {
    if (this.avPlayer === null) {
      return;
    }
    if (this.status === PlayConstants.STATUS_START) {
      this.avPlayer.pause();
    } else {
      this.avPlayer.play();
    }
  }

  setSeekTime(value: number, mode: SliderChangeMode) {
    if (mode === Number(SliderMode.MOVING)) {
      this.playerModel.progressVal = value;
      this.playerModel.currentTime = this.secondToTime(Math.floor(value * this.duration /
      PlayConstants.ONE_HUNDRED / PlayConstants.A_THOUSAND));
    }
    if (mode === Number(SliderMode.END) || mode === Number(SliderMode.CLICK)) {
      this.seekTime = value * this.duration / PlayConstants.ONE_HUNDRED;
      if (this.avPlayer !== null) {
        this.avPlayer.seek(this.seekTime, media.SeekMode.SEEK_PREV_SYNC);
      }
    }
  }

  getStatus() {
    return this.status;
  }

  initProgress(time: number) {
    let nowSeconds = Math.floor(time / PlayConstants.A_THOUSAND);
    let totalSeconds = Math.floor(this.duration / PlayConstants.A_THOUSAND);
    this.playerModel.currentTime = this.secondToTime(nowSeconds);
    this.playerModel.totalTime = this.secondToTime(totalSeconds);
    this.playerModel.progressVal = Math.floor(nowSeconds * PlayConstants.ONE_HUNDRED / totalSeconds);
  }

  resetProgress() {
    this.seekTime = PlayConstants.PROGRESS_SEEK_TIME;
    this.playerModel.currentTime = PlayConstants.PROGRESS_CURRENT_TIME;
    this.playerModel.progressVal = PlayConstants.PROGRESS_PROGRESS_VAL;
  }

  watchStatus() {
    let windowClass = GlobalContext.getObject('windowClass') as window.Window;
    if (this.status === PlayConstants.STATUS_START) {
      windowClass.setWindowKeepScreenOn(true);
    } else {
      windowClass.setWindowKeepScreenOn(false);
    }
  }

  setVideoSize() {
    if (this.avPlayer === null) {
      return;
    }
    // 判断 16:9 还是 4:3
    let ratio = this.avPlayer.width / this.avPlayer.height;
    console.info("width " + this.avPlayer.width + " height " + this.avPlayer.height);
  }

  playError(e: BusinessError) {
    promptAction.showToast({
      duration: PlayConstants.PLAY_ERROR_TIME,
      message: JSON.stringify(e),
    });
  }

  getPlayModel() {
    return this.playerModel;
  }

  switchSurfaceId(newSurfaceId: string): string {
    if (this.avPlayer) {
      // surfaceId 相同无需设置
      if (newSurfaceId == this.surfaceId) {
        console.warn("player does not switch player");
      } else if (this.avPlayer.state === AvplayerStatus.PREPARED
        || this.avPlayer.state === AvplayerStatus.PLAYING
        || this.avPlayer.state === AvplayerStatus.PAUSED
        || this.avPlayer.state === AvplayerStatus.COMPLETED
        || this.avPlayer.state === AvplayerStatus.STOPPED) {
        // prepared/playing/paused/completed/stopped 下可重新设置
        this.surfaceId == newSurfaceId;
      } else {
        console.warn("player does not switch player");
      }
    }
    return this.surfaceId;
  }

  secondToTime(seconds: number): string {
    let hourUnit = PlayConstants.TIME_UNIT * PlayConstants.TIME_UNIT;
    let hour = Math.floor(seconds / hourUnit);
    let minute = Math.floor((seconds - hour * hourUnit) / PlayConstants.TIME_UNIT);
    let second = seconds - hour * hourUnit - minute * PlayConstants.TIME_UNIT;
    if (hour > 0) {
      return `${this.padding(hour.toString())}${':'}
${this.padding(minute.toString())}${':'}${this.padding(second.toString())}`;
    }
    if (minute > 0) {
      return `${this.padding(minute.toString())}${':'}${this.padding(second.toString())}`;
    } else {
      return `${PlayConstants.INITIAL_TIME_UNIT}${':'}${this.padding(second.toString())}`;
    }
  }

  padding(num: string): string {
    let length = PlayConstants.PADDING_LENGTH;
    for (let len = (num.toString()).length; len < length; len = num.length) {
      num = `${PlayConstants.PADDING_STR}${num}`;
    }
    return num;
  }

  // session 相关
  public async createAvSession(name: string, type: avSession.AVSessionType) {
    this.mAvSession = await avSession.createAVSession(GlobalContext.getContext(), name, type);
    await this.mAvSession.activate();
    this.setListenerForMesFromController();
  }

  public async setMediaMetaInfo(assetId: string, title: string, duration: number) {
    let metadata: avSession.AVMetadata = {
      assetId: assetId, // 由应用指定,用于标识应用媒体库里的媒体
      title: title,
      duration: duration,
    };
    await this.mAvSession?.setAVMetadata(metadata);
  }

  public async setPlayingState(avState: avSession.PlaybackState) {
    if (this.avPlayer) {
      let playbackState: avSession.AVPlaybackState = {
        state: avState, // 播放状态
        position: {
          elapsedTime: this.avPlayer.currentTime, // 已经播放的位置,以ms为单位
          updateTime: new Date().getTime(), // 应用更新当前位置时的时间戳,以ms为单位
        },
        speed: 1.0, // 可选,默认是1.0,播放的倍速,按照应用内支持的speed进行设置,系统不做校验
        bufferedTime: 14000, // 可选,资源缓存的时间,以ms为单位
      };
      await this.mAvSession?.setAVPlaybackState(playbackState);
    }
  }

  public async setPauseState() {
    let playbackState: avSession.AVPlaybackState = {
      state: avSession.PlaybackState.PLAYBACK_STATE_PAUSE, // 播放状态
    };
    await this.mAvSession?.setAVPlaybackState(playbackState);
  }

  public seekByTime(time: number) {
    this.avPlayer?.seek(time);
  }

  public async destroyAvSession() {
    await this.mAvSession?.destroy();
  }

  public setListenerForMesFromController() {
    this.mAvSession?.on('play', () => {
      this.play();
    });
    this.mAvSession?.on('pause', () => {
      this.pause();
    });
  }

  public unregisterSessionListener() {
    this.mAvSession?.off('play');
    this.mAvSession?.off('pause');
  }

  // 健康检查
  public checkPlayerHealth() {
    setInterval(() => {
      if (this.avPlayer !== null) {
        // 一直卡在 initialized 阶段
        if (this.avPlayer.state === AvplayerStatus.INITIALIZED) {
          this.errorCount += 1;
        }
        // 健康检查失败一定次数,发送重试状态
        if (this.errorCount == 3) {
          emitter.emit(PlayConstants.PLAY_ERROR_EVENT);
        }
      }
    }, 1000);
  }
}
分享
微博
QQ
微信
回复
2025-01-10 10:15:37
相关问题
AVplayer开发音频播放功能
1406浏览 • 1回复 待解决
基于AVPlayer音频后台播放
862浏览 • 1回复 待解决
AVPlayer实现音频播放(c++侧)
1654浏览 • 1回复 待解决
HarmonyOS 音频播放相关
224浏览 • 1回复 待解决
HarmonyOS音频播放问题
685浏览 • 1回复 待解决
HarmonyOS 音频播放设备的切换
619浏览 • 1回复 待解决
HarmonyOS 音频播放帧率控制
429浏览 • 1回复 待解决
HarmonyOS 音频录制与播放
1026浏览 • 1回复 待解决
SoundPool实现音频播放功能
1641浏览 • 1回复 待解决
HarmonyOS ohaudio音频播放设备切换问题
267浏览 • 1回复 待解决
HarmonyOS 播放器后台暂停音频播放
206浏览 • 1回复 待解决
HarmonyOS 播放音频的示例
210浏览 • 1回复 待解决
HarmonyOS 音频播放相关问题咨询
488浏览 • 2回复 待解决
HarmonyOS 音频后台播放问题
723浏览 • 1回复 待解决
OH _Audio播放音频问题
2493浏览 • 1回复 待解决