WDPlayerController.ets
14.9 KB
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import media from '@ohos.multimedia.media';
import prompt from '@ohos.promptAction';
import { PlayerConstants, AVPlayerStatus, Events } from '../constants/PlayerConstants';
import { BusinessError } from '@ohos.base';
import { TrackingPlay } from 'wdTracking/Index';
import { ParamType } from 'wdTracking/Index';
import { DateTimeUtils, Logger } from 'wdKit/Index';
import { BackgroundAudioController } from './BackgroundAudioController';
import { audio } from '@kit.AudioKit';
interface obj {
loop: boolean
}
const TAG = "WDPlayerController"
@Observed
export class WDPlayerController {
private initPromise: Promise<void>;
private avPlayer?: media.AVPlayer | null;
private duration: number = 0;
private status: number = PlayerConstants.STATUS_IDLE;
private loop: boolean = true;
private url: string = '';
private surfaceId: string = ''; // 若播放音频,无需设置surfaceId
private playSpeed: number = 1;
private seekTime: number = 0;
private positionY: number = 0;
private startTime: number = 0;
private pageParam: ParamType = {}
private pageName: string = ''
private creatStartTime:number = 0;//开始加载时间
private creatEndTime:number = 0;//加载完成时间
private prepareTime:number = 0; //加载时间
private currentPlayTime:number = 0; //当前播放时间
public onVideoSizeChange?: (width: number, height: number) => void;
public onLoaded?: (loaded: number) => void;
public onTimeUpdate?: (position: number, duration: number) => void;
public onVolumeUpdate?: (volume: number) => void;
public continue?: () => void;
public onCanplay?: () => void;
public onStatusChange?: (status: number) => void;
public onSeekDone?: (time: number) => void;
public xComponentController?: XComponentController
public videoWidth: number = 0
public videoHeight: number = 0
public keepOnBackground = false
constructor(obj?: obj) {
Logger.error("初始化")
this.initPromise = this.createAVPlayer();
if(obj?.loop === false) {
this.loop = false
}
}
/**
* 创建 videoPlayer对象
*/
private createAVPlayer(): Promise<void> {
return new Promise((resolve, reject) => {
Logger.debug(TAG, "开始创建")
media.createAVPlayer().then((avPlayer) => {
if (avPlayer) {
Logger.debug(TAG, "创建完成1")
this.avPlayer = avPlayer;
this.bindState();
resolve();
} else {
Logger.error(TAG, "创建完成0")
Logger.error(TAG, '[PlayVideoModel] createAvPlayer fail!');
reject();
}
}).catch((error: BusinessError) => {
Logger.error(TAG, `AVPlayer catchCallback, error message:${error.message}`);
});
;
});
}
/**
* AVPlayer 绑定事件.
*/
private bindState() {
this.avPlayer?.on(Events.STATE_CHANGE, async (state) => {
if (this.avPlayer == null) {
return
}
switch (state) {
case AVPlayerStatus.IDLE:
this.resetProgress();
this.avPlayer.url = this.url;
break;
case AVPlayerStatus.INITIALIZED:
if (this.surfaceId) {
this.avPlayer.surfaceId = this.surfaceId;
}
if(this.onLoaded) {
this.onLoaded(1)
}
// 【华为验收】使用音频场景streamusage错误:STREAM_USAGE_MUSIC(音乐),应改为STREAM_USAGE_MOVIE(电影或视频),可以降低功耗
this.avPlayer.audioRendererInfo = {
usage: audio.StreamUsage.STREAM_USAGE_MOVIE,
rendererFlags: 0
}
this.avPlayer?.prepare();
break;
case AVPlayerStatus.PREPARED:
this.avPlayer.videoScaleType = 0;
if (this.startTime) {
this.setSeekTime(this.startTime, SliderChangeMode.Begin);
}
// this.avPlayer.play();
this.duration = this.avPlayer.duration;
if (this.onCanplay) {
this.onCanplay()
}
this.avPlayer.loop = this.loop
break;
case AVPlayerStatus.PLAYING:
if(this.onLoaded) {
this.onLoaded(2)
}
this.setBright();
this.status = PlayerConstants.STATUS_START;
this.avPlayer!.videoScaleType = media.VideoScaleType.VIDEO_SCALE_TYPE_FIT
this.watchStatus();
break;
case AVPlayerStatus.PAUSED:
this.status = PlayerConstants.STATUS_PAUSE;
this.watchStatus();
break;
case AVPlayerStatus.COMPLETED:
// this.titleThis.playSpeed = 1;
if (this.continue) {
this.continue();
} else {
if(this.loop) {
this.duration = 0;
this.url = this.avPlayer.url || '';
this.avPlayer.reset();
}
this.status = PlayerConstants.STATUS_COMPLETION;
this.watchStatus();
}
break;
case AVPlayerStatus.RELEASED:
this.avPlayer.release();
this.status = PlayerConstants.STATUS_STOP;
this.watchStatus();
Logger.info(TAG, '[PlayVideoModel] state released called')
break;
default:
Logger.info(TAG, '[PlayVideoModel] unKnown state: ' + state);
break;
}
});
this.avPlayer?.on(Events.TIME_UPDATE, (time: number) => {
this.initProgress(time);
});
this.avPlayer?.on(Events.ERROR, (error) => {
// this.playError(error.message);
Logger.error(TAG, '播放错误' + JSON.stringify(error))
TrackingPlay.videoPlayError(error.message, this.pageName, this.pageName, this.pageParam)
})
this.avPlayer?.on('seekDone', (time: number) => {
this.initProgress(time);
if (this.onSeekDone) {
this.onSeekDone(time);
}
})
this.avPlayer?.on(Events.VIDEO_SIZE_CHANGE, (width: number, height: number) => {
if (this.onVideoSizeChange) {
this.onVideoSizeChange(width, height);
}
this.videoWidth = width
this.videoHeight = height
})
}
public setXComponentController(controller: XComponentController) {
this.surfaceId = controller.getXComponentSurfaceId()
this.xComponentController = controller
}
setSurfaceId(surfaceId: string) {
this.surfaceId = surfaceId
}
async firstPlay(url: string,pageId?: string, pageName?: string, pageParam?: ParamType) {
this.url = url;
//加载时长prepareTime
this.creatStartTime = DateTimeUtils.getTimeStamp()
Logger.debug(TAG, '开始创建' + JSON.stringify(this.creatStartTime))
this.prepareTime = 0
if(pageName){
this.pageName = pageName
}
if(pageParam){
this.pageParam = pageParam
}
if (this.avPlayer == null) {
Logger.debug(TAG, "等待")
this.initPromise = this.createAVPlayer();
await this.initPromise;
} else {
if (this.avPlayer.state != AVPlayerStatus.IDLE) {
await this.avPlayer.stop()
await this.avPlayer.release()
this.initPromise = this.createAVPlayer();
await this.initPromise;
}
}
if (this.avPlayer == null) {
return
}
Logger.debug(TAG, "开始播放", this.url)
this.avPlayer.url = this.url;
//加载时长prepareTime
this.creatEndTime = DateTimeUtils.getTimeStamp()
this.prepareTime = 0
this.prepareTime = Math.floor((this.creatEndTime - this.creatStartTime)/1000)
Logger.debug(TAG, '开始播放2',JSON.stringify(this.prepareTime))
}
async release() {
// if (this.avPlayer == null) {
// await this.initPromise;
// }
if (this.avPlayer == null) {
return
}
this.avPlayer.release()
this.avPlayer = null
}
async pause() {
// if (this.avPlayer == null) {
// await this.initPromise;
// }
// if (this.avPlayer == null) {
// return
// }
Logger.debug(TAG, "start pause")
this.avPlayer?.pause();
}
async play() {
// if (this.avPlayer == null) {
// await this.initPromise;
// }
// if (this.avPlayer == null) {
// return
// }
this.avPlayer?.prepare().then(() => {
this.avPlayer?.play()
}, (err: BusinessError) => {
console.error('Failed to prepare,error message is :' + err.message)
})
}
async startRenderFrame(cb: Function) {
this.avPlayer?.on('startRenderFrame', () => {
cb && cb();
Logger.debug(TAG, 'startRenderFrame success')
})
}
async stop() {
// if (this.avPlayer == null) {
// await this.initPromise;
// }
// if (this.avPlayer == null) {
// return
// }
this.avPlayer?.stop();
}
async setLoop() {
// if (this.avPlayer == null) {
// await this.initPromise;
// }
// if (this.avPlayer == null) {
// return
// }
this.loop = !this.loop;
}
async setSpeed(playSpeed: number) {
// if (this.avPlayer == null) {
// await this.initPromise;
// }
// if (this.avPlayer == null) {
// return
// }
if (this.avPlayer && PlayerConstants.OPERATE_STATE.indexOf(this.avPlayer?.state) === -1) {
return;
}
this.playSpeed = playSpeed;
this.avPlayer?.setSpeed(this.playSpeed);
}
async switchPlayOrPause() {
// if (this.avPlayer == null) {
// await this.initPromise;
// }
// if (this.avPlayer == null) {
// return
// }
if (this.status === PlayerConstants.STATUS_START) {
Logger.debug(TAG, "start pause 1111")
this.avPlayer?.pause();
} else {
this.avPlayer?.play();
}
}
async setSeekTime(value: number, mode: SliderChangeMode) {
// if (this.avPlayer == null) {
// await this.initPromise;
// }
// if (this.avPlayer == null) {
// return
// }
// if (mode == SliderChangeMode.Begin) {
// this.seekTime = value * 1000;
// this.avPlayer?.seek(this.seekTime, media.SeekMode.SEEK_PREV_SYNC);
// }
// 防止seek报错
if (this.avPlayer && PlayerConstants.OPERATE_STATE.indexOf(this.avPlayer?.state) === -1) {
return;
}
if (mode === SliderChangeMode.Moving) {
// this.progressThis.progressVal = value;
// this.progressThis.currentTime = DateFormatUtil.secondToTime(Math.floor(value * this.duration /
// 100 / 1000));
}
if (mode === SliderChangeMode.End) {
// Logger.warn(`cj2024 seekTime = ${value}`)
// Logger.warn(`cj2024 duration = ${this.duration}`)
this.seekTime = Math.floor(value * this.duration / 100);
// Logger.warn(`cj2024 seekTime = ${this.seekTime}`)
this.currentPlayTime = this.seekTime
this.avPlayer?.seek(this.seekTime,media.SeekMode.SEEK_CLOSEST);
}
}
async setSeekMicroSecondsTime(value: number) {
// 防止seek报错
if (this.avPlayer && PlayerConstants.OPERATE_STATE.indexOf(this.avPlayer?.state) === -1) {
return;
}
this.avPlayer?.seek(value);
if (this.status == PlayerConstants.STATUS_PAUSE) {
this.avPlayer?.play()
}
}
setBright() {
// globalThis.windowClass.setWindowBrightness(this.playerThis.bright)
}
getStatus() {
return this.status;
}
getPlayer() {
return this.avPlayer;
}
initProgress(time: number) {
this.currentPlayTime=Math.floor(time / 1000);
let nowSeconds = Math.floor(time / 1000);
let totalSeconds = Math.floor(this.duration / 1000);
if (this.keepOnBackground) {
BackgroundAudioController.sharedController().setSessionPlayProgress(time, this.duration)
}
if (this.onTimeUpdate) {
this.onTimeUpdate(time, this.duration);
}
}
resetProgress() {
this.seekTime = 0;
// this.progressThis.currentTime = '00:00';
// this.progressThis.progressVal = 0;
}
resetPlay() {
this.duration = 0;
this.url = this.avPlayer?.url || '';
this.avPlayer?.reset();
}
onVolumeActionStart(event: GestureEvent) {
this.positionY = event.offsetY;
}
onBrightActionStart(event: GestureEvent) {
this.positionY = event.offsetY;
}
volume: number = 1
onVolumeActionUpdate(event: GestureEvent) {
if (!this.avPlayer) {
return
}
if (PlayerConstants.OPERATE_STATE.indexOf(this.avPlayer.state) === -1) {
return;
}
let changeVolume = (event.offsetY - this.positionY) / 300;
let currentVolume = this.volume - changeVolume;
if (currentVolume > 1) {
currentVolume = 1;
}
if (currentVolume <= 0) {
currentVolume = 0;
}
this.volume = currentVolume;
this.avPlayer?.setVolume(this.volume);
this.positionY = event.offsetY;
if (this.onVolumeUpdate) {
this.onVolumeUpdate(this.volume);
}
Logger.debug(TAG, "volume : " + this.volume)
}
onBrightActionUpdate(event: GestureEvent) {
// if (!this.playerThis.volumeShow) {
// this.playerThis.brightShow = true;
// let changeBright = (this.positionY - event.offsetY) / globalThis.screenHeight;
// let currentBright = this.playerThis.bright + changeBright;
// let brightMinFlag = currentBright <= 0;
// let brightMaxFlag = currentBright > 1;
// this.playerThis.bright = brightMinFlag ? 0 :
// (brightMaxFlag ? 1 : currentBright);
// this.setBright();
// this.positionY = event.offsetY;
// }
}
onActionEnd() {
setTimeout(() => {
this.positionY = 0;
}, 200);
}
watchStatus() {
if (this.keepOnBackground) {
BackgroundAudioController.sharedController().setSessionPlayStatus(this.status)
}
Logger.debug(TAG, 'watchStatus ' + this.status)
if(this.status == PlayerConstants.STATUS_START){
// Logger.debug(TAG, '播放视频')
// Logger.debug(TAG, '播放视频prepareTime' + JSON.stringify(this.prepareTime))
// Logger.debug(TAG, '播放视频pageName' + JSON.stringify(this.pageName))
// Logger.debug(TAG, '播放视频pageParam' + JSON.stringify(this.pageParam))
// 播放埋点
TrackingPlay.videoPositivePlay(Number(this.prepareTime),this.pageName, this.pageName, this.pageParam)
}
if(this.status == PlayerConstants.STATUS_COMPLETION){
let initDuration = Math.floor(Number(this.duration)/1000)
// Logger.debug(TAG, '播放结束')
// Logger.debug(TAG, '播放结束currentPlayTime' + JSON.stringify(this.currentPlayTime))
// Logger.debug(TAG, '播放结束initDuration' + JSON.stringify(initDuration))
// Logger.debug(TAG, '播放结束pageName' + JSON.stringify(this.pageName))
// Logger.debug(TAG, '播放结束pageParam' + JSON.stringify(this.pageParam))
// 播放结束埋点
TrackingPlay.videoPlayEnd(this.currentPlayTime, initDuration, this.currentPlayTime, this.pageName, this.pageName, this.pageParam)
}
if (this.onStatusChange) {
this.onStatusChange(this.status)
}
// if (this.status === PlayConstants.STATUS_START) {
// globalThis.windowClass.setWindowKeepScreenOn(true);
// } else {
// globalThis.windowClass.setWindowKeepScreenOn(false);
// }
}
playError(msg?: string) {
prompt.showToast({
duration: 3000,
message: msg ? msg : "请检查地址输入正确且网络正常"
});
}
setStartTime(time?: number) {
this.startTime = time ?? 0;
}
}