index.uts 9.7 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1 2 3
import { media } from '@kit.MediaKit';
import { audio } from '@kit.AudioKit';

DCloud-yyl's avatar
DCloud-yyl 已提交
4
import { InnerAudioContext, CreateInnerAudioContext, type ICreateInnerAudioContextFail } from '../interface.uts';
DCloud-yyl's avatar
DCloud-yyl 已提交
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
import { API_CREATE_INNER_AUDIO_CONTEXT } from '../protocol.uts';
import { getFdFromUriOrSandBoxPath, isFileUri, isSandboxPath, AudioPlayerCallback, AudioPlayerError } from './utils.uts';

const AUDIOS: Record<string, InnerAudioContext | undefined> = {}
const AUDIO_PLAYERS: Record<string, media.AudioPlayer | undefined> = {}

const LOG = (msg: string) => console.log(`[createInnerAudioContext]: ${msg}`)

class STATE_TYPE {
  // 音频播放空闲
  static IDLE: string = 'idle'
  // 音频正在播放
  static PLAYING: string = 'playing'
  // 音频暂停播放
  static PAUSED: string = 'paused'
  // 音频停止播放
  static STOPPED: string = 'stopped'
  // 错误状态
  static ERROR: string = 'error'
}

class AudioPlayer implements InnerAudioContext {
  private audioPlayerCallback: AudioPlayerCallback = new AudioPlayerCallback()

  private _volume: number = 1
  private _src: string = ''
  private _autoplay: boolean = false
  private _startTime: number = 0
  private _buffered: number = 0
  private _title: string = ''
  private audioId: string = ''
  private _playbackRate: number = 1;

  readonly obeyMuteSwitch: boolean = false;

  constructor(audioId: string) {
    this.audioId = audioId
    this.init()
  }

  init() {
    AUDIO_PLAYERS[this.audioId]?.on('dataLoad', () => {
      this.audioPlayerCallback.canPlay()
    });

    AUDIO_PLAYERS[this.audioId]?.on('play', () => {
      this.audioPlayerCallback.play()
    });

    AUDIO_PLAYERS[this.audioId]?.on('pause', () => {
      this.audioPlayerCallback.pause()
    });

    AUDIO_PLAYERS[this.audioId]?.on('finish', () => {
      this.audioPlayerCallback.ended()
    });

    AUDIO_PLAYERS[this.audioId]?.on('timeUpdate', res => {
      this.audioPlayerCallback.timeUpdate(res / 1000)
    });

    AUDIO_PLAYERS[this.audioId]?.on('error', (err) => {
      this.audioPlayerCallback.error(new AudioPlayerError(err.message, err.code))
    });
    AUDIO_PLAYERS[this.audioId]?.on('bufferingUpdate', (infoType, value) => {
      console.info(`[AdvancedAPI] audioPlayer bufferingUpdate ${infoType} ${value}`)
      if (infoType === media.BufferingInfoType.BUFFERING_PERCENT && value !== 0 && AUDIO_PLAYERS[this.audioId]) {
        this._buffered = value;
        if ((AUDIO_PLAYERS[this.audioId]!.currentTime / 1000) >= (AUDIO_PLAYERS[this.audioId]!.duration * value / 100000)) {
          this.audioPlayerCallback.waiting()
        }
      }
    });
    AUDIO_PLAYERS[this.audioId]?.on('audioInterrupt', (InterruptEvent) => {
      console.info('[AdvancedAPI]  audioInterrupt:' + JSON.stringify(InterruptEvent));
      if (AUDIO_PLAYERS[this.audioId] && InterruptEvent.hintType === audio.InterruptHint.INTERRUPT_HINT_PAUSE) {
        AUDIO_PLAYERS[this.audioId]!.pause();
      }
    });
  }
  get duration() {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (!audioPlayer) { return 0 }
    return audioPlayer.duration / 1000;
  }
  get currentTime() {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (!audioPlayer) { return 0 }
    return audioPlayer.currentTime / 1000;
  }
  get paused() {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (!audioPlayer) { return false }
    return audioPlayer.state === STATE_TYPE.PAUSED
  }
  get loop() {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (!audioPlayer) { return false }
    return audioPlayer.loop;
  }
  set loop(value) {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (audioPlayer) {
      audioPlayer.loop = value;
    }
  }
  get volume() {
    return this._volume;
  }
  set volume(value) {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (audioPlayer) {
      this._volume = value;
      audioPlayer.setVolume(value);
    }
  }
  get src() {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (!audioPlayer) { return '' }
    return audioPlayer.src;
  }
  set src(value) {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (typeof value !== 'string') {
      this.audioPlayerCallback.error(new AudioPlayerError(`set src: ${value} is not string`, 10004))
      return;
    }
    if (!audioPlayer) {
      this.audioPlayerCallback.error(new AudioPlayerError(`player is not exist`, 10001))
      return;
    }
    if (!value || !(value.startsWith('http:') || value.startsWith('https:') || isFileUri(value) || isSandboxPath(value))) {
      LOG(`set src: ${value} is invalid`);
      return;
    }
    let path: string = '';
    if (value.startsWith('http:') || value.startsWith('https:')) {
      path = value;
    }
    else if (isFileUri(value) || isSandboxPath(value)) {
      try {
        const fd = getFdFromUriOrSandBoxPath(value);
        path = `fd://${fd}`;
      }
      catch (error) {
        console.error(`${JSON.stringify(error)}`);
      }
    }
    if (audioPlayer.src && path !== audioPlayer.src) {
      audioPlayer.reset();
    }
    AUDIO_PLAYERS[this.audioId]!.src = path;
    this._src = value;
    if (this._autoplay) {
      audioPlayer.play();
      if (this._startTime) {
        audioPlayer.seek(this._startTime);
      }
    }
  }
  get startTime() {
    return this._startTime / 1000;
  }
  set startTime(time: number) {
    this._startTime = time * 1000;
  }
  get autoplay() {
    return this._autoplay;
  }
  set autoplay(flag) {
    this._autoplay = flag;
  }
  get buffered() {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (!audioPlayer) return 0
    return audioPlayer.duration * this._buffered / 100000;
  }
  set playbackRate(rate: number) {
    this.audioPlayerCallback.error(new AudioPlayerError('HarmonyOS Next Audio setting playbackRate is not supported.', -1))
  }
  get playbackRate() {
    return this._playbackRate
  }
  play() {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (!audioPlayer) {
      return;
    }
    const state = audioPlayer.state ?? '';
    if (![STATE_TYPE.PAUSED, STATE_TYPE.STOPPED, STATE_TYPE.IDLE].includes(state)) {
      return;
    }
    if (this._src && audioPlayer.src === '') {
      this.src = this._src;
    }
    audioPlayer.play();
  }
  pause() {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (!audioPlayer) { return; }

    const state = audioPlayer.state;

    if (STATE_TYPE.PLAYING !== state) { return; }
    audioPlayer.pause();
  }
  stop() {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (!audioPlayer) { return; }
    if (![STATE_TYPE.PAUSED, STATE_TYPE.PLAYING].includes(audioPlayer.state)) { return; }

    audioPlayer.stop();
    this.audioPlayerCallback.stop();
    audioPlayer.release();
  }
  seek(position: number) {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (!audioPlayer) { return; }
    const state = audioPlayer.state;
    if (![STATE_TYPE.PAUSED, STATE_TYPE.PLAYING].includes(state)) {
      return;
    }
    this.audioPlayerCallback.seeking()
    audioPlayer.seek(position * 1000);
    this.audioPlayerCallback.seeked()
  }
  destroy() {
    const audioPlayer = AUDIO_PLAYERS[this.audioId];
    if (!audioPlayer) { return; }

    audioPlayer.release();
    AUDIO_PLAYERS[this.audioId] = undefined
    AUDIOS[this.audioId] = undefined
  }
  onCanplay(callback: (result: any) => void): void {
    this.audioPlayerCallback.onCanplay(callback)
  }
  onPlay(callback: (result: any) => void): void {
    this.audioPlayerCallback.onPlay(callback)
  }
  onPause(callback: (result: any) => void): void {
    this.audioPlayerCallback.onPause(callback)
  }
  onStop(callback: (result: any) => void): void {
    this.audioPlayerCallback.onStop(callback)
  }
  onEnded(callback: (result: any) => void): void {
    this.audioPlayerCallback.onEnded(callback)
  }
  onTimeUpdate(callback: (result: any) => void): void {
    this.audioPlayerCallback.onTimeUpdate(callback)
  }
DCloud-yyl's avatar
DCloud-yyl 已提交
257
  onError(callback: (result: ICreateInnerAudioContextFail) => void): void {
DCloud-yyl's avatar
DCloud-yyl 已提交
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
    this.audioPlayerCallback.onError(callback)
  }
  onWaiting(callback: (result: any) => void): void {
    this.audioPlayerCallback.onWaiting(callback)
  }
  onSeeking(callback: (result: any) => void): void {
    this.audioPlayerCallback.onSeeking(callback)
  }
  onSeeked(callback: (result: any) => void): void {
    this.audioPlayerCallback.onSeeked(callback)
  }
  offCanplay(callback: (result: any) => void): void {
    this.audioPlayerCallback.offCanplay(callback)
  }
  offPlay(callback: (result: any) => void): void {
    this.audioPlayerCallback.offPlay(callback)
  }
  offPause(callback: (result: any) => void): void {
    this.audioPlayerCallback.offPause(callback)
  }
  offStop(callback: (result: any) => void): void {
    this.audioPlayerCallback.offStop(callback)
  }
  offEnded(callback: (result: any) => void): void {
    this.audioPlayerCallback.offEnded(callback)
  }
  offTimeUpdate(callback: (result: any) => void): void {
    this.audioPlayerCallback.offTimeUpdate(callback)
  }
DCloud-yyl's avatar
DCloud-yyl 已提交
287
  offError(callback: (result: ICreateInnerAudioContextFail) => void): void {
DCloud-yyl's avatar
DCloud-yyl 已提交
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
    this.audioPlayerCallback.offError(callback)
  }
  offWaiting(callback: (result: any) => void): void {
    this.audioPlayerCallback.offWaiting(callback)
  }
  offSeeking(callback: (result: any) => void): void {
    this.audioPlayerCallback.offSeeking(callback)
  }
  offSeeked(callback: (result: any) => void): void {
    this.audioPlayerCallback.offSeeked(callback)
  }
}

function createAudioInstance() {
  const audioId = `${Date.now()}${Math.random()}`
  // NOTE 避免被 vue Proxy 污染
  AUDIO_PLAYERS[audioId] = media.createAudioPlayer()
  AUDIOS[audioId] = new AudioPlayer(audioId)
  return audioId
}

export const createInnerAudioContext: CreateInnerAudioContext =
  defineSyncApi<InnerAudioContext>(
    API_CREATE_INNER_AUDIO_CONTEXT,
    () => {
      const audioId = createAudioInstance()
      return AUDIOS[audioId]
    }
  ) as CreateInnerAudioContext