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

HarmonyOS
2025-01-10 08:51:05
860浏览
收藏 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);
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
  • 222.
  • 223.
  • 224.
  • 225.
  • 226.
  • 227.
  • 228.
  • 229.
  • 230.
  • 231.
  • 232.
  • 233.
  • 234.
  • 235.
  • 236.
  • 237.
  • 238.
  • 239.
  • 240.
  • 241.
  • 242.
  • 243.
  • 244.
  • 245.
  • 246.
  • 247.
  • 248.
  • 249.
  • 250.
  • 251.
  • 252.
  • 253.
  • 254.
  • 255.
  • 256.
  • 257.
  • 258.
  • 259.
  • 260.
  • 261.
  • 262.
  • 263.
  • 264.
  • 265.
  • 266.
  • 267.
  • 268.
  • 269.
  • 270.
  • 271.
  • 272.
  • 273.
  • 274.
  • 275.
  • 276.
  • 277.
  • 278.
  • 279.
  • 280.
  • 281.
  • 282.
  • 283.
  • 284.
  • 285.
  • 286.
  • 287.
  • 288.
  • 289.
  • 290.
  • 291.
  • 292.
  • 293.
  • 294.
  • 295.
  • 296.
  • 297.
  • 298.
  • 299.
  • 300.
  • 301.
  • 302.
  • 303.
  • 304.
  • 305.
  • 306.
  • 307.
  • 308.
  • 309.
  • 310.
  • 311.
  • 312.
  • 313.
  • 314.
  • 315.
  • 316.
  • 317.
  • 318.
  • 319.
  • 320.
  • 321.
  • 322.
  • 323.
  • 324.
  • 325.
  • 326.
  • 327.
  • 328.
  • 329.
  • 330.
  • 331.
  • 332.
  • 333.
  • 334.
  • 335.
  • 336.
  • 337.
  • 338.
  • 339.
  • 340.
  • 341.
  • 342.
  • 343.
  • 344.
  • 345.
  • 346.
  • 347.
  • 348.
  • 349.
  • 350.
  • 351.
  • 352.
  • 353.
  • 354.
  • 355.
  • 356.
  • 357.
  • 358.
  • 359.
  • 360.
  • 361.
  • 362.
  • 363.
  • 364.
  • 365.
  • 366.
  • 367.
  • 368.
  • 369.
  • 370.
  • 371.
  • 372.
  • 373.
  • 374.
  • 375.
  • 376.
  • 377.
  • 378.
  • 379.
  • 380.
  • 381.
  • 382.
  • 383.
  • 384.
  • 385.
  • 386.
  • 387.
  • 388.
  • 389.
  • 390.
  • 391.
  • 392.
  • 393.
  • 394.
  • 395.
  • 396.
  • 397.
  • 398.
  • 399.
  • 400.
  • 401.
  • 402.
  • 403.
  • 404.
  • 405.
  • 406.
  • 407.
  • 408.
  • 409.
  • 410.
  • 411.
  • 412.
  • 413.
  • 414.
  • 415.
  • 416.
  • 417.
  • 418.
  • 419.
  • 420.
  • 421.
  • 422.
  • 423.
  • 424.
  • 425.
  • 426.
  • 427.
  • 428.
  • 429.
  • 430.
  • 431.
  • 432.
  • 433.
  • 434.
  • 435.
  • 436.
  • 437.
  • 438.
  • 439.
  • 440.
  • 441.
  • 442.
  • 443.
  • 444.
  • 445.
  • 446.
  • 447.
  • 448.
  • 449.
分享
微博
QQ
微信
回复
2025-01-10 10:15:37
相关问题
基于AVPlayer音频后台播放
1374浏览 • 1回复 待解决
AVplayer开发音频播放功能
1795浏览 • 1回复 待解决
HarmonyOS 音频播放设备的切换
1227浏览 • 1回复 待解决
HarmonyOS 音频播放相关
678浏览 • 1回复 待解决
HarmonyOS音频播放问题
1123浏览 • 1回复 待解决
AVPlayer实现音频播放(c++侧)
2181浏览 • 1回复 待解决
HarmonyOS ohaudio音频播放设备切换问题
644浏览 • 1回复 待解决
HarmonyOS 音频录制与播放
1541浏览 • 1回复 待解决
HarmonyOS 音频播放帧率控制
928浏览 • 1回复 待解决
HarmonyOS avplayer播放amr音频的码率问题
573浏览 • 1回复 待解决
SoundPool实现音频播放功能
2171浏览 • 1回复 待解决
HarmonyOS 播放器后台暂停音频播放
748浏览 • 1回复 待解决
HarmonyOS 音频后台播放问题
1286浏览 • 1回复 待解决
HarmonyOS 播放音频的示例
655浏览 • 1回复 待解决
HarmonyOS 音频播放相关问题咨询
1249浏览 • 2回复 待解决
OH _Audio播放音频问题
3066浏览 • 1回复 待解决