• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 播放器demo
2
31. 导入模块
4```js
5import audio from '@ohos.multimedia.audio';
6import PlayerModel from '../../common/PlayerModel.js';
7import AVSessionManager from '@ohos.multimedia.avsession';
8import WantAgent from '@ohos.wantAgent';
9import display from '@ohos.display';
10import multimedia_image from '@ohos.multimedia.image';
11import featureAbility from '@ohos.ability.featureAbility';
12import process from '@ohos.process';
13```
14
152.demo代码
16
17```js
18
19export default {
20    // 定义变量,请开发者根据实际情况使用
21    data: {
22        container:'',
23        div_image:'',
24        titleCss:'',
25        lyricCss:'',
26        div_but:'',
27        btn:'',
28        image:'',
29        btn_image:'',
30        bell_div:'',
31        slider_value:'',
32        slider:'',
33        btn1:'',
34        btn2:'',
35        deviceIdNew:null,
36        btnCss:'',
37        logListCss:'',
38        listLog:'',
39        btnS:'',
40        isShowRk:false,
41        isShowWgr:true,
42        btnC:'',
43        timeEnd:0,
44        musicValue:0,
45        intervalID:0,
46        deviceArr:[],
47        time: (new Date()).getTime(),
48        assetIdArr:[],
49        title: 'dynamic.wav',
50        audioUrl: 'common/images/pause.png',
51        loopModeUrl: 'common/images/ic_public_list_cycle1.png',
52        artist:'品冠',
53        lyric:'dynamic.wav-品冠的歌词',
54        duration:1,
55        index: 0,
56        audioPlayer: null,
57        isSwitching: false,
58        playerModel: new PlayerModel(),
59        audioManager: null,
60        volume: 0,
61        mediaFavorite: false,
62        favoriteBtn:'btn1',
63        currentSession: null,
64        currentProgress: 0,
65        logList: ['log日志显示'],
66        loopMode: 1,
67        speedMode: 'x1',
68        speedArr: ['x1','x2','x0.5'],
69        speedArrSet: [1.0,2.0,0.5],
70        speedIndex: 0,
71        mediaImage:'common/images/bg-tv.jpg',
72        durationMin:'0:00',
73        loopModeArr: ['common/images/ic_public_list_cycle1.png','common/images/ic_public_single_cycle2.png',
74        'common/images/ic_public_order_play3.png','common/images/ic_public_random4.png'],
75        pixelMap:undefined,
76        context:undefined,
77        deviceId:[],
78        deviceName:[],
79    },
80
81    // 日志
82    log(log) {
83        this.logList.unshift(this.logList.length + ': ' + JSON.stringify(log));
84    },
85
86    async onInit() {
87        this.log("onInit start");
88        console.info(' ttt AVSessionPlayer[IndexPage] onInit start');
89        // 横竖屏幕适配
90        display.getDefaultDisplay((err, data) => {
91            if ( data.width > data.height ) {
92                console.info(' ttt AVSessionPlayer[IndexPage] getDefaultDisplay direction is horizontal.[width]' +
93                data.width + '[height]' + data.height);
94                this.container = 'W_container';
95                this.div_image = 'W_div-image';
96                this.image = 'W_image';
97                this.titleCss = 'W_title';
98                this.lyricCss = 'W_lyric';
99                this.div_but = 'W_div-but';
100                this.btn = 'W_btn';
101                this.btn_image = 'W_btn-image';
102                this.bell_div = 'W_bell-div';
103                this.slider_value = 'W_slider-value';
104                this.slider = 'W_slider';
105                this.btnCss = 'W_';
106                this.btnC = 'W_btnC';
107                this.favoriteBtn = 'W_btn1';
108                this.logListCss = 'W_logList';
109                this.listLog = 'W_listLog';
110                this.btnS = 'W_btnS';
111                this.isShowWgr = true;
112                this.isShowRk= false;
113            } else {
114                console.info(' ttt AVSessionPlayer[IndexPage] getDefaultDisplay direction is vertical.[width]' +
115                data.width + '[height]' + data.height);
116                this.container = 'container';
117                this.div_image = 'div-image';
118                this.image = 'image';
119                this.titleCss = 'title';
120                this.lyricCss = 'lyric';
121                this.div_but = 'div-but';
122                this.btn = 'btn';
123                this.btn_image = 'btn-image';
124                this.bell_div = 'bell-div';
125                this.slider_value = 'slider-value';
126                this.slider = 'slider';
127                this.btnCss = '';
128                this.favoriteBtn = 'btn1';
129                this.logListCss = 'logList';
130                this.listLog = 'listLog';
131                this.btnS = 'btn';
132                this.btnC = 'btn';
133                this.isShowRk= true;
134                this.isShowWgr = false;
135
136            }
137        });
138
139        this.context = await featureAbility.getContext();
140        this.audioUrl = 'common/images/pause.png';                           // 请开发者根据实际情况使用
141        this.loopModeUrl = 'common/images/ic_public_list_cycle1.png';        // 请开发者根据实际情况使用
142
143        this.playerModel.setOnStatusChangedListener((isPlaying) => {
144            this.log("setOnStatusChangedListener success ");
145            console.info(' ttt AVSessionPlayer[IndexPage] on player status changed, isPlaying=' + isPlaying + ', refresh ui');
146            if (isPlaying) {
147                this.audioUrl = 'common/images/play.png';
148                this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY,
149                    position:{elapsedTime:this.musicValue,
150                        updateTime:this.onTime()}}).then(() =>{
151                }).catch ((e) => {
152                    this.log("error " + e.message);
153                });
154                this.playMusic();
155            } else {
156                clearInterval(this.intervalID);
157                this.audioUrl = 'common/images/pause.png';
158                this.playerModel.pause();
159                clearInterval(this.intervalID);
160                this.playerModel.seek(this.musicValue);
161                this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PAUSE,
162                    position:{elapsedTime:this.musicValue,
163                        updateTime:this.onTime()}}).then(() => {
164                }).catch ((e) => {
165                    this.log("error " + e.message);
166                });
167            }
168        });
169        this.playerModel.getPlaylist(() => {
170            this.log('getPlaylist ok');
171            console.info(' ttt AVSessionPlayer[IndexPage] getPlaylist ok');
172        });
173        this.setPageData();
174        this.audioManager = await audio.getAudioManager();
175
176        this.log('getAudioManager ok');
177        AVSessionManager.on('sessionServiceDie', (descriptor) => {
178            this.log('sessionServiceDie success');
179        });
180
181        // 创建avSession会话并激活
182        AVSessionManager.createAVSession(this.context,'AVSessionPlayer', 'audio').then(async(session) => {
183            this.log('createAVSession success');
184            console.info("ttt AVSessionPlayer[IndexPage] createAVSession success");
185            this.currentSession = session;
186            await this.currentSession.activate(() => {
187                this.log('activate success');
188            });
189            // 获取输出设备信息
190            this.currentSession.getOutputDevice((err,outputDeviceInfo)=> {
191                this.log("getOutputDevice success");
192                if (outputDeviceInfo && outputDeviceInfo.isRemote) {
193                    this.log('getOutputDevice success  1' + JSON.stringify(outputDeviceInfo.isRemote));
194                    this.log('getOutputDevice success  2' + JSON.stringify(outputDeviceInfo.audioDeviceId));
195                    this.log('getOutputDevice success  2' + JSON.stringify(outputDeviceInfo.deviceName));
196                    if (outputDeviceInfo.audioDeviceId && outputDeviceInfo.deviceName) {
197                        for (let i = 0; i < outputDeviceInfo.audioDeviceId.length; i++) {
198                            let tem = {
199                                deviceId:outputDeviceInfo.audioDeviceId[i],
200                                deviceName:outputDeviceInfo.deviceName[i]
201                            }
202                            this.deviceArr.push(tem);
203                        }
204                    } else {
205                        this.log("getOutputDevice empty data");
206                    }
207                } else {
208                    this.log("getOutputDevice empty data");
209                }
210            });
211
212            this.currentSession.setAudioStreamId([0,10,20]);
213            let metadata = this.setMetaData();
214            // 设置会话元数据
215            this.currentSession.setAVMetadata(metadata,() => {
216                this.log('onInit setAVMetadata success');
217                console.info(' ttt AVSessionPlayer[IndexPage] onInit  setAVMetadata');
218            });
219            // 设置会话播放状态
220            this.currentSession.setAVPlaybackState({
221                speed:this.speedIndex,loopMode:AVSessionManager.LoopMode.LOOP_MODE_SEQUENCE,
222                position:{elapsedTime:0,updateTime:this.onTime()}
223            }, () => {
224                this.log('onInit setAVPlaybackState success');
225                console.info(' ttt AVSessionPlayer[IndexPage] setAVPlaybackState');
226            });
227
228            // 设置启动ability
229            let wantAgentInfo = {
230                wants: [
231                    {
232                        bundleName: this.context.getAbilityInfo().bundleName,
233                        abilityName: this.context.getAbilityInfo().name
234                    }
235                ],
236                operationType: WantAgent.OperationType.START_ABILITIES,
237                requestCode: 0,
238                wantAgentFlags: [WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
239            };
240            WantAgent.getWantAgent(wantAgentInfo,(err,agent) => {
241                WantAgent.getBundleName(agent).then((name) => {
242                    console.info('[ttt] AVSessionPlayer[IndexPage] getBundleName bundle name:' + name);
243                    this.log('getWantAgent success');
244                }, e => {
245                    console.error('[ttt] AVSessionPlayer[IndexPage] getBundleName error' +  ' is ' + e.message);
246                });
247                this.currentSession.setLaunchAbility(agent,() => {
248                    this.log('setLaunchAbility success ');
249                });
250            });
251
252            // 注册播放命令监听
253            this.currentSession.on('play', () => {
254                if (this.isSwitching) {
255                    console.info(' ttt AVSessionPlayer[IndexPage] onPlayClick ignored, isSwitching');
256                    return;
257                }
258                this.log('on Play success callBack');
259                console.info(' ttt AVSessionPlayer[IndexPage] on Play success, isPlaying=' + this.playerModel.isPlaying + 'callBack');
260                this.playerModel.preLoad(this.index, () => {
261                    this.playerModel.play(-1, true);
262                });
263                this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY,
264                    position:{elapsedTime:this.musicValue,
265                        updateTime:this.onTime()}}).then(() =>{
266                }).catch ((e) => {
267                    this.log("error " + e.message);
268                });
269                this.playMusic();
270            });
271
272            // 注册暂停命令监听
273            this.currentSession.on('pause', () => {
274                if (this.isSwitching) {
275                    console.info(' ttt AVSessionPlayer[IndexPage] onPlayClick ignored, isSwitching');
276                    return;
277                }
278                clearInterval(this.intervalID);
279                this.log('on Pause success callBack');
280                console.info(' ttt AVSessionPlayer[IndexPage] onPause success, isPlaying ' + this.playerModel.isPlaying + 'callBack');
281                this.playerModel.pause();
282                this.playerModel.seek(this.musicValue);
283                this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PAUSE,
284                    position:{elapsedTime:this.musicValue, updateTime:this.onTime()}});
285            });
286
287            // 注册停止命令监听
288            this.currentSession.on('stop', () => {
289                this.log('on Stop success callBack');
290                console.info(' ttt AVSessionPlayer[IndexPage] stop success callBack');
291                this.playerModel.stop();
292                this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_STOP,
293                    position:{elapsedTime:this.musicValue,updateTime:this.onTime()}});
294            });
295
296            // 注册上一首命令监听
297            this.currentSession.on('playPrevious', () => {
298                if (this.isSwitching) {
299                    console.info(' ttt AVSessionPlayer[IndexPage] onPreviousClick ignored, isSwitching');
300                    return;
301                }
302                clearInterval(this.intervalID);
303                this.log('on PlayPrevious success callBack');
304                console.info(' ttt AVSessionPlayer[IndexPage] onPrevious success callBack');
305                this.index--;
306                this.musicValue = 0;
307                this.playerModel.seek(0);
308                if (this.index < 0 && this.playerModel.playlist.audioFiles.length >= 1) {
309                    this.index = this.playerModel.playlist.audioFiles.length - 1;
310                }
311                this.currentProgress = 0;
312                this.isSwitching = true;
313                this.playerModel.preLoad(this.index, () => {
314                    this.playerModel.play(0, true);
315                    this.isSwitching = false;
316                });
317                this.setFavorite();
318                this.setPageData();
319
320                this.currentSession.setAVMetadata(this.setMetaData());
321                this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY,
322                    position:{elapsedTime:this.musicValue,updateTime:this.onTime()},
323                    bufferedTime:2000,isFavorite:this.mediaFavorite})
324                this.playMusic();
325                console.info(' ttt AVSessionPlayer[IndexPage] onPreviousClick callBack');
326
327            });
328
329            // 注册下一首命令监听
330            this.currentSession.on('playNext', () => {
331                if (this.isSwitching) {
332                    console.info(' ttt AVSessionPlayer[IndexPage] playNext event is running.');
333                    return;
334                }
335                clearInterval(this.intervalID);
336                this.log('onPlayNext callBack success ');
337                console.info(' ttt AVSessionPlayer[IndexPage] set playNext success callback.');
338                this.index++;
339                this.musicValue = 0;
340                if (this.index >= this.playerModel.playlist.audioFiles.length) {
341                    this.index = 0;
342                }
343                this.currentProgress = 0;
344                this.playerModel.seek(0);
345                this.isSwitching = true;
346                this.playerModel.preLoad(this.index, () => {
347                    this.playerModel.play(0, true);
348                    this.isSwitching = false;
349                });
350                this.setFavorite();
351                this.setPageData();
352                this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY,
353                    position:{elapsedTime:0,updateTime:this.onTime()},
354                    bufferedTime:2000,isFavorite:this.mediaFavorite});
355                this.currentSession.setAVMetadata(this.setMetaData());
356
357                console.info(' ttt AVSessionPlayer[IndexPage] playNext - setAVMetadata author:' + metadata.author +
358                ', publishDate:' + metadata.publishDate);
359                this.playMusic();
360                console.info(' ttt AVSessionPlayer[IndexPage] set playNext callback.' + this.title + ':' + this.artist);
361            });
362
363            // 注册播放快进命令监听
364            this.currentSession.on('fastForward', () => {
365                this.log('on FastForward success callBack');
366                console.info(' ttt AVSessionPlayer[IndexPage] fastForward success callBack');
367            });
368
369            // 注册播放快退命令监听
370            this.currentSession.on('rewind', () => {
371                this.log('on Rewind success callBack');
372                console.info(' ttt AVSessionPlayer[IndexPage] rewind success callBack');
373            });
374
375            // 注册跳播命令监听
376            this.currentSession.on('seek', (time) => {
377                this.log('on Seek success callBack');
378                console.info(' ttt AVSessionPlayer[IndexPage] seek success callBack is :' + time);
379                this.musicValue = time;
380                this.playerModel.seek(this.musicValue);
381                this.currentSession.setAVPlaybackState({ position:{elapsedTime:this.musicValue,updateTime:this.onTime()},
382                    bufferedTime:2000});
383
384            });
385
386            // 注册设置播放速度命令监听
387            this.currentSession.on('setSpeed', (speed) => {
388                this.log('on SetSpeed success callBack');
389                console.info(' ttt AVSessionPlayer[IndexPage] set Speed success callBack is :' + speed);
390                this.speedIndex = speed;
391                this.speedMode = this.speedArr[this.speedIndex];
392                this.currentSession.setAVPlaybackState({
393                    speed:this.speedIndex
394                }, () => {
395                    console.info(' ttt AVSessionPlayer[IndexPage] onSetSpeed');
396                });
397            });
398
399            // 注册设置播放循环模式命令监听
400            this.currentSession.on('setLoopMode', (mode) => {
401                this.log('on SetLoopMode success callBack');
402                console.info(' ttt AVSessionPlayer[IndexPage] setLoopMode success callBack is:' + mode);
403                if (mode == 0) {
404                    this.loopMode = 1;
405                    this.loopModeUrl = 'common/images/ic_public_list_cycle1.png';
406                    this.currentSession.setAVPlaybackState({loopMode:AVSessionManager.LoopMode.LOOP_MODE_SEQUENCE});
407                } else if (mode == 1) {
408                    this.loopMode = 2;
409                    this.loopModeUrl = 'common/images/ic_public_single_cycle2.png';
410                    this.currentSession.setAVPlaybackState({loopMode:AVSessionManager.LoopMode.LOOP_MODE_SINGLE});
411                } else if (mode == 2) {
412                    this.loopMode = 3;
413                    this.loopModeUrl = 'common/images/ic_public_order_play3.png';
414                    this.currentSession.setAVPlaybackState({loopMode:AVSessionManager.LoopMode.LOOP_MODE_LIST});
415                } else if (mode == 3) {
416                    this.loopMode = 4;
417                    this.loopModeUrl = 'common/images/ic_public_random4.png';
418                    this.currentSession.setAVPlaybackState({loopMode:AVSessionManager.LoopMode.LOOP_MODE_SHUFFLE});
419                }
420            });
421
422            // 注册设置歌曲收藏命令监听
423            this.currentSession.on('toggleFavorite', (assetId) => {
424                this.log('on ToggleFavorite success callBack');
425                console.info(' ttt AVSessionPlayer[IndexPage] toggleFavorite success callBack, assetId: ' + assetId);
426                this.mediaFavorite = this.mediaFavorite == false? true : false;
427                if (this.mediaFavorite) {
428                    this.favoriteBtn = this.btnCss + 'btn2';
429                    this.assetIdArr.push(this.playerModel.playlist.audioFiles[this.index].assetId);
430                } else {
431                    this.favoriteBtn = this.btnCss + 'btn1';
432                    this.deleteAssetId();
433                }
434                this.currentSession.setAVPlaybackState({isFavorite:this.mediaFavorite});
435            });
436
437            // 注册媒体按键命令监听
438            this.currentSession.on('handleKeyEvent', (event) => {
439                this.log('on HandleKeyEvent success callBack ');
440                console.info(' ttt AVSessionPlayer[IndexPage] handleKeyEvent success callBack,event is: ' + JSON.stringify(event));
441            });
442
443            // 注册播放设备变化命令监听
444            this.currentSession.on('outputDeviceChanged', (device) => {
445                this.log('on OutputDeviceChanged success callBack ');
446                console.info(' ttt AVSessionPlayer[IndexPage] outputDeviceChanged success callBack, is: ' + device.deviceName);
447            });
448        }, e => {
449            console.info(' ttt AVSessionPlayer[IndexPage] createAVSession log code is ' + e.code + 'message is' + e.message);
450        }).then(()=>{
451            let state = {
452                state: AVSessionManager.PlaybackState.PLAYBACK_STATE_STOP,
453                speed: 1.0,
454                position: {elapsedTime:0, updateTime:this.onTime()},
455                bufferedTime: 2000,
456                loopMode: AVSessionManager.LoopMode.LOOP_MODE_SEQUENCE,
457                isFavorite: false,
458            };
459            this.currentSession.setAVPlaybackState(state);
460            console.info(' ttt AVSessionPlayer[IndexPage] setAVPlaybackState state complete.');
461        }).then(()=>{
462            console.info(' ttt AVSessionPlayer[IndexPage] this.currentSession is activate.');
463            //            return this.currentSession.activate();
464        }), e => {
465            console.info(' ttt AVSessionPlayer[IndexPage] createAVSession code is ' + e.code + 'message is' + e.message);
466        }
467    },
468
469    // 释放资源
470    onDestroy() {
471        this.log('onDestroy Start');
472        console.info(' ttt AVSessionPlayer[IndexPage] this.currentSession is destroy.');
473        this.currentSession.off('handleKeyEvent');
474        this.currentSession.off('seek');
475        this.currentSession.off('play');
476        this.currentSession.off('pause');
477        this.currentSession.off('stop');
478        this.currentSession.off('playNext');
479        this.currentSession.off('playPrevious');
480        this.currentSession.off('fastForward');
481        this.currentSession.off('rewind');
482        this.currentSession.off('setSpeed');
483        this.currentSession.off('setLoopMode');
484        this.currentSession.off('toggleFavorite');
485        this.currentSession.off('outputDeviceChanged');
486        this.currentSession.deactivate().then(() => {
487            this.currentSession.destroy();
488        });
489        this.log('onDestroy end');
490    },
491
492    // 设置循环模式
493    onSetLoopMode() {
494        this.log('onSetLoopMode Start');
495        console.info(' ttt AVSessionPlayer[IndexPage] onSetLoopMode ' + this.loopMode + this.loopModeUrl);
496        this.loopMode++;
497        if (this.loopMode > 4) {
498            this.loopMode = 1;
499        }
500        if (this.loopMode == 1) {
501            this.loopModeUrl = 'common/images/ic_public_list_cycle1.png';
502            this.currentSession.setAVPlaybackState({loopMode:AVSessionManager.LoopMode.LOOP_MODE_SEQUENCE});
503        } else if (this.loopMode == 2) {
504            this.loopModeUrl = 'common/images/ic_public_single_cycle2.png';
505            this.currentSession.setAVPlaybackState({loopMode:AVSessionManager.LoopMode.LOOP_MODE_SINGLE});
506        } else if (this.loopMode == 3) {
507            this.loopModeUrl = 'common/images/ic_public_order_play3.png';
508            this.currentSession.setAVPlaybackState({loopMode:AVSessionManager.LoopMode.LOOP_MODE_LIST});
509        } else if (this.loopMode == 4) {
510            this.loopModeUrl = 'common/images/ic_public_random4.png';
511            this.currentSession.setAVPlaybackState({loopMode:AVSessionManager.LoopMode.LOOP_MODE_SHUFFLE});
512        } else {
513            this.loopModeUrl = 'common/images/ic_public_list_cycle1.png';
514            this.currentSession.setAVPlaybackState({loopMode:AVSessionManager.LoopMode.LOOP_MODE_SEQUENCE});
515        }
516        console.info(' ttt AVSessionPlayer[IndexPage] onSetLoopMode 22 ' + this.loopMode + this.loopModeUrl);
517    },
518
519    // 设置播放速度
520    onSetSpeed() {
521        this.log('onSetLoopMode start');
522        this.speedIndex++;
523        if (this.speedIndex > 2) {
524            this.speedIndex = 0
525        }
526        this.speedMode = this.speedArr[this.speedIndex];
527        this.currentSession.setAVPlaybackState({
528            speed:this.speedIndex
529        }, () => {
530            console.info(' ttt AVSessionPlayer[IndexPage] onSetSpeed');
531        });
532    },
533
534    // 点击播放
535    onPlayClick() {
536        this.log('onPlayClick start');
537        if (this.isSwitching) {
538            console.info(' ttt AVSessionPlayer[IndexPage] onPlayClick ignored, isSwitching');
539            return;
540        }
541        console.info(' ttt AVSessionPlayer[IndexPage] onPlayClick, isPlaying=' + this.playerModel.isPlaying);
542        if (this.playerModel.isPlaying) {
543            this.playerModel.pause();
544            this.playerModel.seek(this.musicValue);
545            clearInterval(this.intervalID);
546            this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PAUSE,
547                position:{elapsedTime:this.musicValue,updateTime:this.onTime()}, bufferedTime:2000});
548        } else {
549            this.playerModel.preLoad(this.index, () => {
550                this.playerModel.play(-1, true);
551                this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY,
552                    position:{elapsedTime:this.musicValue,updateTime:this.onTime()}});
553                this.playMusic();
554
555            });
556        }
557    },
558
559    // 播放音乐
560    playMusic() {
561        let this_ = this;
562        let startT = this.musicValue;
563        clearInterval(this.intervalID);
564        this.intervalID = setInterval(function() {
565            this_.musicValue += (0.5 * this_.speedArrSet[this_.speedIndex] * 1000);
566            //            this_.playerModel.seek(this_.musicValue);
567            if (this_.musicValue > this_.playerModel.playlist.audioFiles[this_.index].duration) {
568                this_.musicValue = 0;
569                if (this_.loopMode == 1) {
570                    this_.onNextClick();
571                    clearInterval(this_.intervalID);
572                } else if (this_.loopMode == 2) {
573                    this_.musicValue = 0;
574                    this_.playerModel.preLoad(this_.index, () => {
575                        this_.playerModel.play(0, true)
576                        console.info(' ttt AVSessionPlayer[IndexPage] onPlayClick isPlaying :' + this_.playerModel.isPlaying);
577                        this_.isSwitching = false;
578                    });
579
580                } else if (this_.loopMode == 3) {
581                    clearInterval(this_.intervalID);
582                    this_.onNextClick();
583                } else if (this_.loopMode == 4) {
584                    clearInterval(this_.intervalID);
585                    this_.index = Math.floor(Math.random()*4);
586                    this_.onNextClick();
587                }
588            }
589        }, 500);
590        this_.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY,
591            position:{elapsedTime:startT,updateTime:this_.onTime()}, bufferedTime:2000});
592    },
593
594    // 点击上一首
595    onPreviousClick() {
596        this.log('onPreviousClick start')
597        if (this.isSwitching) {
598            console.info(' ttt AVSessionPlayer[IndexPage] onPreviousClick ignored, isSwitching');
599            return;
600        }
601        clearInterval(this.intervalID);
602        console.info(' ttt AVSessionPlayer[IndexPage] onPreviousClick');
603        this.index--;
604        this.musicValue = 0;
605        this.playerModel.seek(0);
606        if (this.index < 0 && this.playerModel.playlist.audioFiles.length >= 1) {
607            this.index = this.playerModel.playlist.audioFiles.length - 1;
608        }
609        this.currentProgress = 0;
610        this.isSwitching = true;
611        this.playerModel.preLoad(this.index, () => {
612            this.playerModel.play(0, true);
613            this.isSwitching = false;
614        });
615        this.setFavorite();
616        this.setPageData();
617
618        this.currentSession.setAVMetadata(this.setMetaData());
619        this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY,
620            position:{elapsedTime:0,updateTime:this.onTime()}, bufferedTime:2000, isFavorite:this.mediaFavorite})
621        console.info(' ttt AVSessionPlayer[IndexPage] onPreviousClick 11111');
622        this.playMusic();
623    },
624
625    // 点击下一首
626    onNextClick() {
627        this.log('onNextClick start');
628        if (this.isSwitching) {
629            console.info(' ttt AVSessionPlayer[IndexPage] onNextClick ignored, isSwitching');
630            return;
631        }
632        clearInterval(this.intervalID);
633        console.info(' ttt AVSessionPlayer[IndexPage] onNextClick');
634        this.index++;
635        this.musicValue = 0;
636        this.playerModel.seek(0);
637        if (this.index >= this.playerModel.playlist.audioFiles.length) {
638            this.index = 0;
639        }
640        this.currentProgress = 0;
641        this.isSwitching = true;
642        let self = this;
643        this.playerModel.preLoad(this.index, () => {
644            self.playerModel.play(0, true);
645            self.isSwitching = false;
646        });
647        this.setFavorite();
648        this.setPageData();
649
650        console.info(" ttt this.setMetaData()0 :  ");
651        let metadata = this.setMetaData()
652        console.info(" ttt this.setMetaData()1 :  " + metadata.mediaImage);
653        this.currentSession.setAVMetadata(metadata);
654        console.info(" ttt this.setMetaData()2 :  " + metadata.mediaImage);
655        this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY,
656            position:{elapsedTime:0,updateTime:this.onTime()}, bufferedTime:2000, isFavorite:this.mediaFavorite})
657        console.info(" ttt this.setMetaData()3 :  " + metadata.mediaImage);
658        this.playMusic();
659    },
660
661    media(e) {
662        this.log('onMedia start')
663        this.volume = e.value
664        this.audioManager.setVolume(audio.AudioVolumeType.MEDIA, this.volume).then(() => {
665            console.info(' ttt Promise returned to indicate a successful volume setting.');
666        });
667    },
668
669    // 设置收藏
670    async setFavorite() {
671        console.info(' ttt AVSessionPlayer[IndexPage] setFavorite1' + this.mediaFavorite);
672        let flg = false;
673        for(let i = 0; i < this.assetIdArr.length; i++) {
674            if (this.assetIdArr[i] == this.playerModel.playlist.audioFiles[this.index].assetId) {
675                console.info(' ttt AVSessionPlayer[IndexPage] setFavorite1 id:' + this.assetIdArr[i] + " assetId:" +
676                this.playerModel.playlist.audioFiles[this.index].assetId);
677                flg = true;
678                break;
679            }
680        }
681        this.mediaFavorite = flg;
682        if (this.mediaFavorite) {
683            this.favoriteBtn = this.btnCss + 'btn2';
684        } else {
685            this.favoriteBtn = this.btnCss + 'btn1';
686        }
687        console.info(' ttt AVSessionPlayer[IndexPage] setFavorite2' + this.mediaFavorite);
688    },
689
690    showPanel() {
691        this.$element('showPanel').show();
692    },
693
694    closePanel() {
695        this.$element('showPanel').close();
696    },
697
698    async toggleFavorite() {
699        this.log('toggleFavorite start');
700        console.info(' ttt AVSessionPlayer[IndexPage] toggleFavorite');
701        this.mediaFavorite = this.mediaFavorite == false? true : false;
702        if (this.mediaFavorite) {
703            this.favoriteBtn = this.btnCss + 'btn2';
704            this.assetIdArr.push(this.playerModel.playlist.audioFiles[this.index].assetId);
705        } else {
706            this.favoriteBtn = this.btnCss + 'btn1';
707            this.deleteAssetId();
708        }
709        this.currentSession.setAVPlaybackState({isFavorite:this.mediaFavorite});
710        console.info(' ttt AVSessionPlayer[IndexPage] toggleFavorite' + this.assetIdArr.toString());
711    },
712    deleteAssetId() {
713        for(let i = 0; i < this.assetIdArr.length; i++) {
714            if (this.assetIdArr[i] == this.playerModel.playlist.audioFiles[this.index].assetId) {
715                this.assetIdArr.splice(i,1);
716            }
717        }
718    },
719    setPageData() {
720        this.title = this.playerModel.playlist.audioFiles[this.index].title;
721        this.artist = this.playerModel.playlist.audioFiles[this.index].artist;
722        this.lyric = this.playerModel.playlist.audioFiles[this.index].lyric;
723        this.duration = this.playerModel.playlist.audioFiles[this.index].duration;
724        this.mediaImage  = this.playerModel.playlist.audioFiles[this.index].mediaImage;
725        console.info('ttt AVSessionPlayer[IndexPage] setPageData - mediaImage' + this.mediaImage);
726        let muv = this.duration/1000
727        let minutes = Math.floor(muv / 60);
728        let seconds = muv % 60;
729        if (seconds.toString().length < 2) {
730            seconds = '0' + seconds.toString();
731        }
732        this.durationMin = minutes.toString() + ':' + seconds.toString();
733    },
734    mediaMusic(e) {
735        console.info('ttt AVSessionPlayer[IndexPage] mediaMusic');
736        this.log('mediaMusic start');
737        let startT = this.musicValue;
738        this.musicValue = e.value;
739        this.playerModel.seek(this.musicValue);
740        if (this.playerModel.isPlaying) {
741            this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY,
742                position:{elapsedTime:startT,updateTime:this.onTime()}, bufferedTime:2000});
743        } else {
744            this.currentSession.setAVPlaybackState({state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PAUSE,
745                position:{elapsedTime:startT,updateTime:this.onTime()}, bufferedTime:2000});
746        }
747    },
748    setMetaData() {
749        return {
750            assetId:this.playerModel.playlist.audioFiles[this.index].assetId,
751            title:this.playerModel.playlist.audioFiles[this.index].title,
752            artist:this.playerModel.playlist.audioFiles[this.index].artist,
753            lyric:this.playerModel.playlist.audioFiles[this.index].lyric,
754            duration:this.playerModel.playlist.audioFiles[this.index].duration,
755            mediaImage:this.playerModel.playlist.audioFiles[this.index].mediaImage,
756            author: this.playerModel.playlist.audioFiles[this.index].author,
757            album: this.playerModel.playlist.audioFiles[this.index].album,
758            writer: this.playerModel.playlist.audioFiles[this.index].writer,
759            composer: this.playerModel.playlist.audioFiles[this.index].composer,
760            publishDate: this.playerModel.playlist.audioFiles[this.index].publishDate,
761            subtitle: this.playerModel.playlist.audioFiles[this.index].subtitle,
762            description: this.playerModel.playlist.audioFiles[this.index].description,
763            previousAssetId: this.playerModel.playlist.audioFiles[this.index].previousAssetId,
764            nextAssetId: this.playerModel.playlist.audioFiles[this.index].nextAssetId
765        }
766    },
767    onTime() {
768        return (new Date()).getTime();
769    },
770    sleep(ms) {
771        return new Promise(resolve => {
772            setTimeout(resolve,ms)
773        })
774    },
775    getDeviceList() {
776        this.log('getDeviceList method');
777        this.$element("eventDialog").show();
778    },
779    getDevice(e) {
780        this.log("getDeviceId success :" + e.newValue);
781        this.deviceIdNew = e.newValue;
782    },
783    changeDevice() {
784        this.$element("eventDialog").close();
785        this.castAudio();
786    },
787
788    // 远端投播
789    async castAudio() {
790        this.log('castAudio method');
791        this.audioManager.getRoutingManager((err,audioRoutingManager) => {
792            this.log('getRoutingManager success');
793            audioRoutingManager.getDevices(4,(err,AudioDeviceDescriptors) => {
794                this.log('getDevices success');
795                if (AudioDeviceDescriptors) {
796                    this.log('getDeviceIds' + JSON.stringify(AudioDeviceDescriptors));
797                    for (let i = 0; i < AudioDeviceDescriptors.length; i++) {
798                        this.log("id = " + AudioDeviceDescriptors[i].id);
799                    }
800                }
801                let token = {
802                    sessionId:this.currentSession.sessionId,
803                    pid:process.pid,
804                    uid:process.uid
805                };
806                AVSessionManager.castAudio(token,AudioDeviceDescriptors,(err) => {
807                    if (err) {
808                        this.log('castAudio err');
809                        console.info(' ttt AVSessionPlayer[IndexPage] castAudio err');
810                    } else {
811                        this.log('castAudio success');
812                        console.info(' ttt AVSessionPlayer[IndexPage] castAudio success');
813                    }
814                });
815            });
816        });
817    },
818    avdestroy() {
819        this.currentSession.destroy();
820    },
821
822    deactive() {
823        this.currentSession.deactivate();
824    },
825
826    active() {
827        this.currentSession.activate();
828    },
829
830    offplay() {
831        this.currentSession.off('play');
832    },
833
834    offpause() {
835        this.currentSession.off('pause');
836    },
837
838    offplaynext() {
839        this.currentSession.off('playNext');
840    },
841
842    offplayprevious() {
843        this.currentSession.off('playPrevious');
844    },
845
846    offseek() {
847        this.currentSession.off('seek');
848    },
849
850    offsetspeed() {
851        this.currentSession.off('setSpeed');
852    },
853
854    offsetloopmode() {
855        this.currentSession.off('setLoopMode');
856    },
857
858    offtogglefavorite() {
859        this.currentSession.off('toggleFavorite');
860    },
861
862    offhandlekeyhevent() {
863        this.currentSession.off('handleKeyEvent');
864    },
865
866    offsessionservicedie() {
867        AVSessionManager.off('sessionServiceDie');
868    },
869}
870
871```
872