AudioSuspensionModel.ets 5.26 KB
import window from '@ohos.window';
import { Logger } from 'wdKit';
import { BackgroundAudioController, WDPlayerController } from 'wdPlayer';
import { BusinessError } from '@ohos.base';
import { EmitterEventId, EmitterUtils } from 'wdKit/Index'

const TAG = 'AudioSuspensionModel'

/**
 * 音频悬浮窗公共方法类
 */
export class AudioSuspensionModel {
  public playerController: SubscribedAbstractProperty<WDPlayerController> =  AppStorage.link<WDPlayerController>('playerController')
  public floatWindowClass: SubscribedAbstractProperty<window.Window> =  AppStorage.link<window.Window>('floatWindowClass')
  public srcTitle: string = ''
  // 窗口是否最小化
  private isMinimize: SubscribedAbstractProperty<boolean> = AppStorage.link<boolean>('isMinimize')
  constructor() {
    this.initPlayerController()
  }
  /**
   * 判断音频实例是否已存在,不存在则创建
   */
  private initPlayerController() {
    if(this.playerController === undefined) {
      // Logger.info(TAG, 'playerController undefined')
      AppStorage.setOrCreate('playerController', new WDPlayerController({loop: false}));
      this.playerController = AppStorage.link<WDPlayerController>('playerController')
      // Logger.info(TAG, 'playerController create success')
      this.playerController.get().onStatusChange = (status: number) => {
        // console.info(TAG, 'this.currentStatus Model', status)
        EmitterUtils.sendEvent(EmitterEventId.AUDIO_CHANGE_STATUS, status)
      }
    } else {
      // Logger.info(TAG, 'playerController already exit')
    }
  }
  /**
   * 配置音频地址
   */
  public async setPlayerUrl(url: string, srcTitle: string, srcContentId?: string, srcSource?: string) {
    // console.log(TAG,'url', url)
    this.playerController.get().keepOnBackground = true
    BackgroundAudioController.sharedController().avplayerController = this.playerController.get()
    await BackgroundAudioController.sharedController().createSession()
    // BackgroundAudioController.sharedController().startContinuousTask()
    BackgroundAudioController.sharedController().listenPlayEvents()
    await BackgroundAudioController.sharedController().setSessionMetaData(srcContentId ?? "", srcTitle, $r("app.media.system_audio_icon_bk_center"), srcSource ?? "")
    BackgroundAudioController.sharedController().activateSession()
    BackgroundAudioController.sharedController().stopUseFeatures()

    if (this.playerController.get().getUrl() === url) {
      this.isMinimize = AppStorage.link<boolean>('isMinimize')
      // console.log(TAG, 'this.isMinimize', this.isMinimize?.get())
      if (this.isMinimize?.get()) {
        EmitterUtils.sendEvent(EmitterEventId.AUDIO_WINDOW_EXPAND, 1)
        AppStorage.setOrCreate('isMinimize', false);
        this.playerController.get().resetPlay()
      } else {
        this.playerController.get().switchPlayOrPause()
      }
    } else {
      this.playerController.get().firstPlay(url)
      this.playerController.get().onCanplay = () => {
        this.playerController.get().play()
      }
      this.srcTitle = srcTitle
      EmitterUtils.sendEvent(EmitterEventId.AUDIO_CHANGE_TITLe, this.srcTitle)
      EmitterUtils.sendEvent(EmitterEventId.AUDIO_WINDOW_EXPAND, 1)
    }
    this.showWindow()
  }
  // 显示悬浮窗。
  public showWindow() {
    // 判断当前窗口是否已显示,使用callback异步回调。
    try {
      let data = this.floatWindowClass.get().isWindowShowing();
      // console.info(TAG, 'window is showing: ' + data);
      if(data === false) {
        // 显示当前窗口,使用callback异步回调。
        this.floatWindowClass.get().showWindow((err: BusinessError) => {
          let errCode: number = err.code;
          if (errCode) {
            // console.error(TAG, 'floatWindowClass Failed to show the window. Cause: ' + JSON.stringify(err));
            return;
          }
          // console.info(TAG, 'floatWindowClass Succeeded in showing the window.');
        });
      }
    } catch (exception) {
      console.error(TAG, `Failed to check whether the window is showing. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }

  // 设置悬浮窗尺寸
  public resizeWindow(width: number, height: number) {
    this.floatWindowClass.get().resize(width, height, (err: BusinessError) => {
      let errCode: number = err.code;
      if (errCode) {
        // console.error(TAG, 'floatWindowClass Failed to change the window size. Cause:' + JSON.stringify(err));
        return;
      }
      // console.info(TAG, 'floatWindowClass Succeeded in changing the window size.');
    });
  }

  // 隐藏悬浮窗
  public minimize() {
    this.floatWindowClass.get().minimize((err: BusinessError) => {
      const errCode: number = err.code;
      if (errCode) {
        // console.error(TAG, 'Failed to minimize the window. Cause: ' + JSON.stringify(err));
        return;
      }
      AppStorage.setOrCreate('isMinimize', true);
      // console.info(TAG, 'Succeeded in minimizing the window.');
    });
  }
  // 获取当前播放状态 newsId作为参数
  public newsInfo() {
    const currentStatus = this.playerController.get().getStatus()
    const url = this.playerController.get().getUrl()
    return JSON.stringify({ currentStatus, url })
  }

  public switchPlayOrPause() {
    this.playerController.get().switchPlayOrPause()
  }



}