• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 播控中心demo
2
31.导入模块
4```js
5import audio from '@ohos.multimedia.audio'
6import WantAgent from '@ohos.wantAgent';
7import process from '@ohos.process';
8import KeyEvent from '@ohos.multimodalInput.keyEvent';
9import PlayerModel from '../../common/PlayerModel.js';
10import AVSessionManager from '@ohos.multimedia.avsession';
11import RemoteDeviceModel from '../../../model/RemoteDeviceModel.js';
12import featureAbility from '@ohos.ability.featureAbility';
13import wantAgent from '@ohos.wantAgent';
14import display from '@ohos.display';
15import image from '@ohos.multimedia.image';
16```
17
182.demo代码
19```js
20var DEVICE_LIST_LOCALHOST;
21export default {
22    // 定义变量,请开发者根据实际情况使用
23    data: {
24        title: 'title',
25        artist: 'artist',
26        audioUrl: 'common/images/pause.png',
27        index: 0,
28        loopModIndex: 0,
29        audioPlayer: undefined,
30        isSwitching: false,
31        audioManager: undefined,
32        isCallingDefault:false,
33        volume: 0,
34        avSessionCtrl: undefined,
35        CenterSupportCmd: new Set(),
36        ValidCmd: new Set(),
37        CurrentTime: 0,
38        CurrentTimeOn:'0:00',
39        isPlaying: false,
40        deviceArr:[],
41        backImg: 'common/images/bg-tv.jpg',
42        musicIcon: 'common/images/music_oh.png',
43        selectDevice: 'common/images/ic_hop.svg',
44        remoteDeviceModel: new RemoteDeviceModel(),
45        showOrHide: false,
46        deviceList: [],
47        deviceId:[],
48        deviceName:[],
49        collectBtn: 'button_release',
50        SetLoopModeBtn: 'button_release',
51        SetSpeedBtn: 'button_release',
52        SetSpeed: 'x' + 1,
53        SetLoopMode: 'common/images/ic_public_list_cycle.png',
54        SetLoopIconArray: [
55            'common/images/ic_public_list_cycle.png',
56            'common/images/ic_public_single_cycle.png',
57            'common/images/ic_public_order_play.png',
58            'common/images/ic_public_random.png'
59        ],
60        SetLoopParam: [
61            AVSessionManager.LoopMode.LOOP_MODE_SEQUENCE,
62            AVSessionManager.LoopMode.LOOP_MODE_SINGLE,
63            AVSessionManager.LoopMode.LOOP_MODE_LIST,
64            AVSessionManager.LoopMode.LOOP_MODE_SHUFFLE
65        ],
66        SetSpeedArray: [
67            1.0,
68            2.0,
69            0.5
70        ],
71        SpeedIndex: 0,
72        AVSessionCon: undefined,
73        music_lyric: undefined,
74        controllerMap: new Map(),
75        container: '',
76        containerCenter: '',
77        deviceInf: '',
78        deviceIdNew:'',
79        duration28:0,
80        duration128:0,
81        duration256:0,
82        musicName: '',
83        musicAuthor: '',
84        musicLyric:'',
85        controlSection: '',
86        deviceListClass: '',
87        deviceListItem: '',
88        deviceItemTitle: '',
89        deviceItemRadio: '',
90        bell_div:'',
91        slider_value:'',
92        slider:'',
93        duration:0,
94        duration68:true,
95        musicValue:0,
96        intervalID:0,
97        durationMin:'',
98        count:0,
99        logList: ['日志'],
100        context:null
101    },
102
103    // 日志
104    log(log) {
105        this.logList.unshift(this.logList.length + ': ' + JSON.stringify(log));
106    },
107    onInit() {
108
109        //横竖屏幕适配
110        display.getDefaultDisplay((err, data) => {
111            if ( data.width > data.height ) {
112                console.info('AVSessionController[IndexPage] getDefaultDisplay direction is horizontal.[width]' + data.width + '[height]' + data.height);
113                this.container         = 'h_container';
114                this.containerCenter   = 'h_container_center';
115                this.deviceInf         = 'h_device_inf';
116                this.musicName         = 'h_music_name';
117                this.musicAuthor       = 'h_music_author';
118                this.musicLyric        = 'h_music_lyric'
119                this.controlSection    = 'h_control_section';
120                this.deviceListClass   = 'h_device_list';
121                this.deviceListItem    = 'h_device_list_item';
122                this.deviceItemTitle   = 'h_device_item_title';
123                this.deviceItemRadio   = 'h_device_item_radio';
124                this.bell_div          = 'h_bell_div';
125                this.slider_value      = 'h_slider_value';
126                this.slider            = 'h_slider';
127            } else {
128                console.info('AVSessionController[IndexPage] getDefaultDisplay direction is vertical.[width]' + data.width + '[height]' + data.height);
129                this.container         = 'v_container';
130                this.containerCenter   = 'v_container_center';
131                this.deviceInf         = 'v_device_inf';
132                this.musicName         = 'v_music_name';
133                this.musicAuthor       = 'v_music_author';
134                this.musicLyric        = 'v_music_lyric'
135                this.controlSection    = 'v_control_section';
136                this.deviceListClass   = 'v_device_list';
137                this.deviceListItem    = 'v_device_list_item';
138                this.deviceItemTitle   = 'v_device_item_title';
139                this.deviceItemRadio   = 'v_device_item_radio';
140                this.bell_div          = 'v_bell_div';
141                this.slider_value      = 'v_slider_value ';
142                this.slider            = 'v_slider ';
143            }
144        });
145
146         // 获取会话描述符,创建控制器
147        AVSessionManager.getAllSessionDescriptors().then((descriptors) => {
148            this.log('getAllSessionDescriptors success');
149            console.info('getAllSessionDescriptors: '+descriptors);
150            descriptors.forEach((descriptor) => {
151                if (descriptor.isActive) {
152                    this.log('isActive success');
153                    console.info('[ttt] AVSessionController[IndexPage] getAllSessionDescriptors session ${tag} is active' + descriptor.sessionTag);
154                    this.AVSessionCon = AVSessionManager.createController(descriptor.sessionId).then((controller) => {
155                        this.controllerMap.set(descriptor.sessionId, controller);
156                        this.log('createController success');
157                        console.info('[ttt] AVSessionController[IndexPage] getAllSessionDescriptors this.avSessionCtrl session success %s, %s', this.avSessionCtrl, controller);
158                        if (descriptor.isTopSession) {
159                            this.avSessionCtrl = controller;
160                            console.info('[ttt] AVSessionController[IndexPage] getAllSessionDescriptors session success.[%d]', descriptor.sessionId);
161                        } else {
162                            console.info('[ttt] AVSessionController[IndexPage] getAllSessionDescriptors session.isTopSession is not [%d] topSession.', descriptor.sessionId);
163                        }
164                    }, e => {
165                        console.error('[ttt] AVSessionController[IndexPage] getAllSessionDescriptors createController' + descriptor.sessionTag + ' is '+ e.code);
166                    })
167                } else {
168                    console.error('[ttt] AVSessionController[IndexPage] getAllSessionDescriptors descriptor.isActive is ' + descriptor.isActive);
169                }
170            })
171        }, e => {
172            console.error('[ttt] AVSessionController[IndexPage] getAllSessionDescriptors error' +  ' is ' + e.message);
173        });
174
175        // 注册会话创建监听
176        AVSessionManager.on('sessionCreate', (descriptor) => {
177            this.log('sessionCreate success');
178            if (descriptor == undefined) {
179                console.error('[ttt] AVSessionController[IndexPage] sessionCreate session is error');
180                return;
181            } else {
182                // 获取会话描述符
183                console.info('[ttt] AVSessionController[IndexPage] sessionCreate start create' + descriptor.sessionTag);
184                this.AVSessionCon = AVSessionManager.createController(descriptor.sessionId).then((controller) => {
185                    this.controllerMap.set(descriptor.sessionId, controller);
186
187                    if (descriptor.isTopSession) {
188                        this.avSessionCtrl = controller;
189                        this.onShow();
190                        console.info('[ttt] AVSessionController[IndexPage] sessionCreate this.avSessionCtrl session success %s, %s', this.avSessionCtrl, controller);
191                    } else {
192                        console.info('[ttt] AVSessionController[IndexPage] sessionCreate session.isTopSession is not topSession.');
193                    }
194                }, e => {
195                    console.error('[ttt] AVSessionController[IndexPage] sessionCreate this.avSessionCtrl createController');
196                })
197            }
198        })
199
200        // Register the system's highest priority session change listening
201        AVSessionManager.on('topSessionChange', (descriptor) => {
202            this.log('topSessionChange success');
203            if (descriptor == undefined) {
204                console.error('[ttt] AVSessionController[IndexPage] topSessionChange session is error');
205                return;
206            } else {
207                // 获取会话播放状态信息
208                let avsession = this.avSessionCtrl;
209                if (avsession != undefined) {
210                    avsession.getAVPlaybackState().then((playState) => {
211                        this.count = 0;
212                        let avPlaybackState = playState.state;
213                        this.CurrentTime = avsession.getRealPlaybackPositionSync();
214                        this.log('CurrentTime: '+this.CurrentTime);
215                        console.info('[ttt] AVSessionController[IndexPage] topSessionChange CurrentTime:' + this.CurrentTime)
216                        console.info('[ttt] AVSessionController[IndexPage] topSessionChange playState:' + playState.state)
217                        if (avPlaybackState == AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY) {
218                            avsession.sendControlCommand({command:'pause'});
219                            this.isPlaying = false;
220                            clearInterval(this.intervalID);
221                            this.audioUrl = 'common/images/pause.png';
222                            console.info('[ttt] AVSessionController[IndexPage] topSessionChange speed:' + playState.speed)
223                        }
224                    });
225                    avsession = undefined;
226                }
227
228                if (descriptor.isTopSession) {
229                    this.avSessionCtrl = this.controllerMap.get(descriptor.sessionId);
230                    console.info('[ttt] AVSessionController[IndexPage] topSessionChange session success.[%d]', descriptor.sessionId);
231                } else {
232                    console.info('[ttt] AVSessionController[IndexPage] topSessionChange session.isTopSession is not [%d] topSession.', descriptor.sessionId);
233                }
234            }
235        })
236
237        // 注册系统会话销毁监听
238        AVSessionManager.on('sessionDestroy', (descriptor) => {
239            this.log('sessionDestroy success.');
240            if (descriptor == undefined) {
241                console.error('[ttt] AVSessionController[IndexPage] sessionDestroy session is error');
242                return;
243            } else if(descriptor.isTopSession) {
244                if (this.avSessionCtrl != undefined) {
245                    this.avSessionCtrl = undefined;
246                }
247                clearInterval(this.intervalID);
248                this.count = 0;
249                this.controllerMap.delete(descriptor.sessionId);
250                this.collectBtn = 'button_release';
251                this.loopModIndex = 0;
252                this.SetLoopMode = this.SetLoopIconArray[this.loopModIndex];
253                this.SpeedIndex = 0;
254                this.SetSpeed = 'x' + this.SetSpeedArray[this.SpeedIndex];
255                this.isPlaying = false;
256                this.audioUrl = 'common/images/pause.png';
257                this.artist = "artist";
258                this.title = "title";
259                this.music_lyric = "lyric";
260            }
261            console.info('[ttt] AVSessionController[IndexPage] sessionDestroy session [%d] success.', descriptor.sessionId);
262        });
263
264        // 初始化设备列表(分布式)
265        DEVICE_LIST_LOCALHOST = {
266            id: 'localDev',
267            name: this.$t('strings.localDev'),
268        };
269        this.deviceList = [DEVICE_LIST_LOCALHOST];
270    },
271
272    async onShow() {
273        await this.AVSessionCon;
274        this.audioManager = await audio.getAudioManager();
275        this.context = await featureAbility.getContext();
276        console.info('[ttt] AVSessionController[IndexPage] onShow this.avSessionCtrl end %s', this.avSessionCtrl);
277        if (this.avSessionCtrl != undefined) {
278            // 获取会话元数据
279            this.avSessionCtrl.getAVMetadata().then((data) => {
280                console.info('getAVMetadata success');
281                this.log('getAVMetadata success');
282                this.artist = data.artist
283                this.title = data.title
284                this.music_lyric = data.lyric
285                this.duration = data.duration;
286                if(data.duration >= 68000 && data.duration <128000){
287                    this.duration68 = true;
288                    this.duration28 = false;
289                    this.duration128 = false;
290                    this.duration256 = false;
291                } else if(data.duration < 68000){
292                    this.duration28 = true;
293                    this.duration68 = false;
294                    this.duration128 = false;
295                    this.duration256 = false;
296                } else if(data.duration >= 128000 && data.duration < 256000){
297                    this.duration28 = false;
298                    this.duration68 = false;
299                    this.duration128 = true;
300                    this.duration256 = false;
301                } else if(data.duration >= 256000){
302                    this.duration28 = false;
303                    this.duration68 = false;
304                    this.duration128 = false;
305                    this.duration256 = true;
306                }
307                let muv = this.duration/1000;
308                let minutes = Math.floor(muv / 60);
309                let seconds = muv % 60;
310                if(seconds.toString().length < 2) {
311                    seconds = '0' + seconds.toString();
312                }
313                this.durationMin = minutes.toString() + ':' + seconds.toString();
314                this.backImg = data.mediaImage;
315                console.info('[ttt] AVSessionController[IndexPage] artist:' + this.artist)
316                console.info('[ttt] AVSessionController[IndexPage] title:' + this.title)
317                console.info('[ttt] AVSessionController[IndexPage] music_lyric:' + this.music_lyric)
318            })
319
320            // 获取会话播放状态信息
321            this.avSessionCtrl.getAVPlaybackState().then((playState) => {
322                console.info('getAVPlaybackState success');
323                this.log('getAVPlaybackState success');
324                let avPlaybackState = playState.state;
325                this.CurrentTime = this.avSessionCtrl.getRealPlaybackPositionSync();
326                this.log('CurrentTime: '+this.CurrentTime);
327                console.info('[ttt] AVSessionController[IndexPage] CurrentTime:' + this.CurrentTime)
328                this.log('sendcontrolcommand success');
329                console.info('sendcontrolcommand success');
330                this.musicValue = Math.floor(this.CurrentTime);
331                let muv = this.musicValue/1000;
332                let minutes = Math.floor(muv / 60);
333                let seconds = muv % 60;
334                if(seconds.toString().length < 2) {
335                    seconds = '0' + seconds.toString();
336                }
337                this.CurrentTimeOn = minutes.toString() + ':' + seconds.toString();
338                console.info('[ttt] AVSessionController[IndexPage] 播放状态:' + playState.state)
339                console.info('[ttt] AVSessionController[IndexPage] 当前播放速度:' + playState.speed)
340                if (avPlaybackState == AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY) {
341                    this.isPlaying = true;
342                    this.onUpdateMusicSlider();
343                    this.audioUrl = 'common/images/play.png';
344                } else {
345                    clearInterval(this.intervalID);
346                    this.isPlaying = false;
347                    this.audioUrl = 'common/images/pause.png';
348                }
349
350                let avPlaybackSpeed = playState.speed;
351                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl playbackStateChange callback speed %s', avPlaybackSpeed);
352                if (avPlaybackSpeed != undefined) {
353                    this.SpeedIndex = avPlaybackSpeed
354                    this.SetSpeed = 'x' + this.SetSpeedArray[avPlaybackSpeed];
355                }
356
357                let isFavorite = playState.isFavorite;
358                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl playbackStateChange callback isFavorite %s', isFavorite);
359                // 发送收藏指令
360                if (isFavorite != undefined) {
361                    if (isFavorite == true) {
362                        this.collectBtn = 'button_press';
363                    } else if (isFavorite == false) {
364                        this.collectBtn = 'button_release';
365                    }
366                }
367
368                let avPlaybackLoopMode = playState.loopMode;
369                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl playbackStateChange callback loopMode %s', avPlaybackLoopMode);
370                if (avPlaybackLoopMode != undefined) {
371                    this.loopModIndex = avPlaybackLoopMode;
372                    this.SetLoopMode = this.SetLoopIconArray[avPlaybackLoopMode];
373                }
374
375                let position = playState.position;
376                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl playbackStateChange callback position %s', position);
377                if (position != undefined) {
378                    if(this.count == 0) {
379                        if(this.isPlaying){
380                            // 发送播放控制命令
381                            this.avSessionCtrl.sendControlCommand({command:'play'});
382                            this.log('sendcontrolcommand success');
383                            console.info('sendcontrolcommand success');
384                        }
385                        this.count++;
386                        this.musicValue = position.elapsedTime;
387                        let muv = this.musicValue/1000;
388                        let minutes = Math.floor(muv / 60);
389                        let seconds = muv % 60;
390                        if(seconds.toString().length < 2) {
391                            seconds = '0' + seconds.toString();
392                        }
393                        this.CurrentTimeOn = minutes.toString() + ':' + seconds.toString();
394                    }
395                }
396            });
397
398            // 获取有效命令集
399            this.avSessionCtrl.getValidCommands().then((command) => {
400                this.log('getValidCommands success');
401                for ( let c of this.CenterSupportCmd) {
402                    if (command.has(c)) {
403                        this.ValidCmd.add(c);
404                    }
405                }
406            });
407
408            // 注册元数据更新监听
409            this.avSessionCtrl.on('metadataChange', 'all', (data) => {
410                this.log('metadataChange success');
411                console.info('metadataChange success');
412                if (data == undefined) {
413                    console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl data is undefined.');
414                    return;
415                }
416                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl metadataChange callback.');
417                this.artist = data.artist?data.artist:this.artist;
418                this.title = data.title?data.title:this.title;
419                this.music_lyric = data.lyric;
420                this.avSessionCtrl.getAVMetadata().then((data1) => {
421
422                    this.artist = data1.artist;
423                    this.title = data1.title;
424                    this.music_lyric = data1.lyric;
425                    this.duration = data1.duration;
426                    if(data.duration >= 68000 && data.duration <128000){
427                        this.duration68 = true;
428                        this.duration28 = false;
429                        this.duration128 = false;
430                        this.duration256 = false;
431                    } else if(data.duration < 68000){
432                        this.duration28 = true;
433                        this.duration68 = false;
434                        this.duration128 = false;
435                        this.duration256 = false;
436                    } else if(data.duration >= 128000 && data.duration < 256000){
437                        this.duration28 = false;
438                        this.duration68 = false;
439                        this.duration128 = true;
440                        this.duration256 = false;
441                    } else if(data.duration >= 256000){
442                        this.duration28 = false;
443                        this.duration68 = false;
444                        this.duration128 = false;
445                        this.duration256 = true;
446                    }
447                    let muv = this.duration/1000;
448                    let minutes = Math.floor(muv / 60);
449                    let seconds = muv % 60;
450                    if(seconds.toString().length < 2) {
451                        seconds = '0' + seconds.toString();
452                    }
453                    this.durationMin = minutes.toString() + ':' + seconds.toString();
454                    this.backImg = data1.mediaImage;
455                    this.onUpdateMusicSlider();
456                })
457
458            });
459
460            // 注册会话销毁监听
461            this.avSessionCtrl.on('sessionDestroy', () => {
462                this.log('AVSessionController destroy success');
463                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl sessionDestroy callback.');
464            });
465
466            // 注册播放状态更新监听
467            this.avSessionCtrl.on('playbackStateChange', 'all', (state) => {
468                this.log('playbackStateChange success');
469                let avPlaybackState = state.state;
470                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl playbackStateChange callback state %s', avPlaybackState);
471                if (avPlaybackState != undefined) {
472                    this.CurrentTime = this.avSessionCtrl.getRealPlaybackPositionSync();
473                    this.log('CurrentTime: '+this.CurrentTime);
474                    this.musicValue = this.CurrentTime;
475                    let muv = this.musicValue/1000;
476                    let minutes = Math.floor(muv / 60);
477                    let seconds = muv % 60;
478                    if(seconds.toString().length < 2) {
479                        seconds = '0' + seconds.toString();
480                    }
481                    this.CurrentTimeOn = minutes.toString() + ':' + seconds.toString();
482                    console.info('[ttt] AVSessionController[IndexPage] playbackStateChange CurrentTime:' + this.CurrentTime)
483                    if (avPlaybackState == AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY) {
484                        this.isPlaying = true;
485                        this.audioUrl = 'common/images/play.png';
486                        this.onUpdateMusicSlider();
487                        console.info('[ttt] AVSessionController[IndexPage] playbackStateChange callback play.');
488                    } else {
489                        clearInterval(this.intervalID);
490                        this.isPlaying = false;
491                        this.audioUrl = 'common/images/pause.png';
492                        console.info('[ttt] AVSessionController[IndexPage] playbackStateChange callback pause.');
493                    }
494                }
495
496                let avPlaybackSpeed = state.speed;
497                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl playbackStateChange callback speed %s', avPlaybackSpeed);
498                if (avPlaybackSpeed != undefined) {
499                    this.SpeedIndex = avPlaybackSpeed
500                    this.SetSpeed = 'x' + this.SetSpeedArray[avPlaybackSpeed];
501                }
502
503                let isFavorite = state.isFavorite;
504                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl playbackStateChange callback isFavorite %s', isFavorite);
505                // 发送收藏指令
506                if (isFavorite != undefined) {
507                    if (isFavorite == true) {
508                        this.collectBtn = 'button_press';
509                    } else if (isFavorite == false) {
510                        this.collectBtn = 'button_release';
511                    }
512                }
513
514                let avPlaybackLoopMode = state.loopMode;
515                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl playbackStateChange callback loopMode %s', avPlaybackLoopMode);
516                if (avPlaybackLoopMode != undefined) {
517                    this.loopModIndex = avPlaybackLoopMode;
518                    this.SetLoopMode = this.SetLoopIconArray[avPlaybackLoopMode];
519                }
520
521                let position = state.position;
522
523                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl playbackStateChange callback position %s', position);
524                if (position != undefined) {
525                    this.musicValue = position.elapsedTime;
526                    let muv = this.musicValue/1000;
527                    let minutes = Math.floor(muv / 60);
528                    let seconds = muv % 60;
529                    if(seconds.toString().length < 2) {
530                        seconds = '0' + seconds.toString();
531                    }
532                    this.CurrentTimeOn = minutes.toString() + ':' + seconds.toString();
533                }
534            });
535
536            // 4.controller 'active state changed' callback.
537            this.avSessionCtrl.on('activeStateChange', (isActive) => {
538                this.log('activeStateChange success');
539
540                if (isActive == undefined) {
541                    console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl state is undefined.');
542                    return;
543                }
544                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl activeStateChange callback.');
545                if (isActive) {
546                    console.info('[ttt] AVSessionController[IndexPage] 按键高亮.');
547                } else {
548                    console.info('[ttt] AVSessionController[IndexPage] 按键无效.');
549                }
550            });
551
552            // 注册会话支持的命令变更监听
553            this.avSessionCtrl.on('validCommandChange', (cmds) => {
554                this.log('validCommandChange success');
555                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl validCommandChange callback.');
556                this.ValidCmd.clear();
557                for (let c of this.CenterSupportCmd) {
558                    if (cmds.has(c)) {
559                        this.ValidCmd.add(c);
560                    }
561                }
562            });
563
564            // 获取输出设备信息
565            this.avSessionCtrl.getOutputDevice((err,outputDeviceInfo)=> {
566                this.log("getOutputDevice success");
567                if (outputDeviceInfo && outputDeviceInfo.isRemote) {
568                    this.log('getOutputDevice success  1' + JSON.stringify(outputDeviceInfo.isRemote));
569                    this.log('getOutputDevice success  2' + JSON.stringify(outputDeviceInfo.audioDeviceId));
570                    this.log('getOutputDevice success  2' + JSON.stringify(outputDeviceInfo.deviceName));
571                    if (outputDeviceInfo.audioDeviceId && outputDeviceInfo.deviceName) {
572                        for (let i = 0; i < outputDeviceInfo.audioDeviceId.length; i++) {
573                            let tem = {
574                                deviceId:outputDeviceInfo.audioDeviceId[i],
575                                deviceName:outputDeviceInfo.deviceName[i]
576                            }
577                            this.deviceArr.push(tem);
578                        }
579                    } else {
580                        this.log("getOutputDevice empty data");
581                    }
582                } else {
583                    this.log("getOutputDevice empty data");
584                }
585            });
586
587            // 注册输出设备变更监听
588            this.avSessionCtrl.on('outputDeviceChange', () => {
589                this.log('outputDeviceChange success');
590                console.info('[ttt] AVSessionController[IndexPage] AVSessionCtrl outputDeviceChange callback.');
591            });
592        }
593    },
594
595    onDestroy() {
596        this.avSessionCtrl.off("validCommandChange");
597        this.avSessionCtrl.off("metadataChange");
598        this.avSessionCtrl.off("outputDeviceChange");
599    },
600
601    onUpdateMusicSlider() {
602        let this_ = this;
603        clearInterval(this.intervalID);
604
605        this.intervalID = setInterval(function() {
606            this_.musicValue += (0.5 * this_.SetSpeedArray[this_.SpeedIndex] * 1000);
607            let muv = this_.musicValue/1000;
608            let minutes = Math.floor(muv / 60);
609            let seconds = Math.floor(muv % 60);
610            if(seconds.toString().length < 2) {
611                seconds = '0' + seconds.toString();
612            }
613            this_.CurrentTimeOn = minutes.toString() + ':' + seconds.toString();
614            if (this_.musicValue > this_.duration && this_.duration != 0) {
615                this_.musicValue = 0;
616                this_.CurrentTimeOn = '0:00';
617                if(this_.loopModIndex == 0) {
618                    clearInterval(this_.intervalID);
619                    this_.onNextClick();
620                } else if (this_.loopModIndex == 1) {
621                    this_.musicValue = 0;
622                    this_.CurrentTimeOn = '0:00';
623                } else if (this_.loopModIndex == 2) {
624                    clearInterval(this_.intervalID);
625                    this_.onNextClick();
626                } else if (this_.loopModIndex == 3) {
627                    clearInterval(this_.intervalID);
628                    this_.index = Math.floor(Math.random()*4);
629                    this_.onNextClick();
630                }
631            }
632        }, 500);
633    },
634
635    // 点击播放
636    onPlayClick() {
637        if (this.avSessionCtrl == undefined) {
638            if (!this.isCallingDefault) {
639                this.isCallingDefault = true;
640                AVSessionManager.createController('default').then((controller) => {
641                    this.controllerMap.set(controller.sessionId, controller);
642                    this.avSessionCtrl = controller;
643                    this.onShow();
644                    console.info('[ttt] AVSessionController[IndexPage] sessionCreate this.avSessionCtrl session success %s, %s', this.avSessionCtrl, controller);
645                }, e => {
646                    console.error('[ttt] AVSessionController[IndexPage] sessionCreate this.avSessionCtrl createfaultController error');
647                })
648                this.isCallingDefault = false;
649            }
650            return;
651        }
652
653        // 判断会话是否激活
654        this.avSessionCtrl.isActive((active) => {
655            if ((active == false) || (active == undefined)) {
656                return;
657            }
658        })
659        console.info('[ttt] AVSessionController[IndexPage] onPlayClick this.avSessionCtrl %s', this.avSessionCtrl);
660        if (this.isPlaying) {
661            clearInterval(this.intervalID);
662            this.isPlaying = false;
663            this.audioUrl = 'common/images/pause.png';
664            // 发送暂停控制命令
665            this.avSessionCtrl.sendControlCommand({command:'pause'});
666            this.log('sendcontrolcommand success');
667            console.info('sendcontrolcommand success');
668            console.info('[ttt] AVSessionController[IndexPage] onPlayClick is pause.');
669        } else {
670            this.onUpdateMusicSlider();
671            this.isPlaying = true;
672            this.audioUrl = 'common/images/play.png';
673            // 发送播放控制命令
674            this.avSessionCtrl.sendControlCommand({command:'play'});
675            this.log('sendcontrolcommand success');
676            console.info('sendcontrolcommand success');
677            console.info('[ttt] AVSessionController[IndexPage] onPlayClick is playing.');
678        }
679    },
680
681    // 点击上一首
682    onPreviousClick() {
683        if (this.avSessionCtrl == undefined) {
684            return;
685        }
686
687        this.avSessionCtrl.isActive((active) => {
688            if ((active == false) || (active == undefined)) {
689                return;
690            }
691        })
692
693        console.info('[ttt] AVSessionController[IndexPage] onPreviousClick');
694        if (this.isPlaying == false) {
695            this.audioUrl = 'common/images/play.png';
696            this.isPlaying = true;
697            this.avSessionCtrl.sendControlCommand({command:'play'});
698            this.log('sendcontrolcommand success');
699            console.info('sendcontrolcommand success');
700        }
701        this.avSessionCtrl.sendControlCommand({command:'playPrevious'});
702        this.log('sendcontrolcommand success');
703        console.info('sendcontrolcommand success');
704        this.onUpdateMusicSlider();
705    },
706
707    // 点击下一首
708    onNextClick() {
709        if (this.avSessionCtrl == undefined) {
710            return;
711        }
712
713        this.avSessionCtrl.isActive((active) => {
714            if ((active == false) || (active == undefined)) {
715                return;
716            }
717        })
718        console.info('[ttt] AVSessionController[IndexPage] onNextClick');
719        if (this.isPlaying == false) {
720            this.audioUrl = 'common/images/play.png';
721            this.isPlaying = true;
722            this.avSessionCtrl.sendControlCommand({command:'play'});
723            this.log('sendcontrolcommand success');
724            console.info('sendcontrolcommand success');
725        }
726        this.avSessionCtrl.sendControlCommand({command:'playNext'});
727        this.log('sendcontrolcommand success');
728        console.info('sendcontrolcommand success');
729        this.onUpdateMusicSlider();
730    },
731
732    media(e) {
733        this.volume = e.value
734        this.audioManager.setVolume(audio.AudioVolumeType.MEDIA, this.volume).then(() => {
735            console.info('Promise returned to indicate a successful volume setting.');
736        })
737    },
738
739    // 流转按钮
740    onSelectDeviceClick() {
741        console.info('[ttt] AVSessionController[IndexPage] onSelectDeviceClick button.');
742        if (!this.showOrHide) {
743            this.selectDevice = 'common/images/ic_hop_blue.svg';
744            this.showOrHide = true;
745        } else {
746            this.selectDevice = 'common/images/ic_hop.svg';
747            this.showOrHide = false;
748            this.remoteDeviceModel.registerDeviceListCallback(() => {
749                var list = [];
750                list[0] = DEVICE_LIST_LOCALHOST;
751                var deviceList;
752                if (this.remoteDeviceModel.discoverList.length > 0) {
753                    deviceList = this.remoteDeviceModel.discoverList;
754                    console.info('[ttt] AVSessionController[IndexPage] discoverList length is ' + this.remoteDeviceModel.discoverList.length);
755                } else {
756                    deviceList = this.remoteDeviceModel.deviceList;
757                    console.info('[ttt] AVSessionController[IndexPage] deviceList length is ' + this.remoteDeviceModel.deviceList.length);
758                }
759                for (var i = 0; i < deviceList.length; i++) {
760                    console.info('[ttt] AVSessionController[IndexPage] device ' + i + '/' + deviceList.length + ' deviceId='
761                    + deviceList[i].deviceId + ' deviceName=' + deviceList[i].deviceName + ' deviceType='
762                    + deviceList[i].deviceType);
763                    list[i + 1] = {
764                        name: deviceList[i].deviceName,
765                        id: deviceList[i].deviceId,
766                    };
767                }
768                this.deviceList = list;
769            });
770            console.info('[ttt] AVSessionController[IndexPage] onContinueAbilityClick end');
771        }
772    },
773
774    onDeviceChange(inputValue, e) {
775        console.info('[ttt] AVSessionController[IndexPage] onDeviceChange ' + inputValue + ', ' + e.value);
776        if (inputValue === e.value) {
777            if (this.remoteDeviceModel.discoverList.length > 0) {
778                console.info('[ttt] AVSessionController[IndexPage] continue to unauthed device');
779                var name = undefined;
780                for (var i = 0; i < this.remoteDeviceModel.discoverList.length; i++) {
781                    if (this.remoteDeviceModel.discoverList[i].deviceId === e.value) {
782                        name = this.remoteDeviceModel.discoverList[i].deviceName;
783                        break;
784                    }
785                }
786                if (name == undefined) {
787                    console.error('[ttt] AVSessionController[IndexPage] onRadioChange failed, can not get name from discoverList');
788                    return;
789                }
790                console.info('[ttt] AVSessionController[IndexPage] onRadioChange name=' + name);
791
792                let self = this;
793                this.remoteDeviceModel.authDevice(e.value, () => {
794                    console.info('[ttt] AVSessionController[IndexPage] auth and online finished');
795                    for (i = 0; i < self.remoteDeviceModel.deviceList.length; i++) {
796                        if (self.remoteDeviceModel.deviceList[i].deviceName === name) {
797                            self.startAbilityContinuation(self.remoteDeviceModel.deviceList[i].deviceId,                                                     self.remoteDeviceModel.deviceList[i].deviceName);
798                        }
799                    }
800                });
801            } else {
802                console.info('[ttt] AVSessionController[IndexPage] continue to authed device');
803                for (i = 0; i < this.remoteDeviceModel.deviceList.length; i++) {
804                    if (this.remoteDeviceModel.deviceList[i].deviceId === e.value) {
805                        this.startAbilityContinuation(this.remoteDeviceModel.deviceList[i].deviceId,                                                     this.remoteDeviceModel.deviceList[i].deviceName);
806                    }
807                }
808            }
809        }
810        this.showOrHide = false;
811        this.selectDevice = 'common/images/ic_hop.svg';
812    },
813
814    getDeviceList() {
815        this.$element("eventDialog").show();
816    },
817    getDevice(e) {
818        this.log("getDeviceId success :" + e.newValue);
819        this.deviceIdNew = e.newValue;
820    },
821    changeDevice() {
822        this.$element("eventDialog").close();
823        this.castAudio();
824    },
825
826    // 远端投播
827    async castAudio() {
828        this.log('castAudio method');
829        this.audioManager.getRoutingManager((err,audioRoutingManager) => {
830            this.log('getRoutingManager success');
831            audioRoutingManager.getDevices(4,(err,AudioDeviceDescriptors) => {
832                this.log('getDevices success');
833                if (AudioDeviceDescriptors) {
834                    this.log('getDeviceIds' + JSON.stringify(AudioDeviceDescriptors));
835                    for (let i = 0; i < AudioDeviceDescriptors.length; i++) {
836                        this.log("id = " + AudioDeviceDescriptors[i].id);
837                    }
838                }
839                let token = {
840                    sessionId:this.avSessionCtrl.sessionId,
841                    pid:process.pid,
842                    uid:process.uid
843                };
844                AVSessionManager.castAudio(token,AudioDeviceDescriptors,(err) => {
845                    if (err) {
846                        this.log('castAudio err');
847                        console.info(' ttt AVSessionPlayer[IndexPage] castAudio err');
848                    } else {
849                        this.log('castAudio success');
850                        console.info(' ttt AVSessionPlayer[IndexPage] castAudio success');
851                    }
852                });
853            });
854        });
855    },
856
857    startAbilityContinuation(deviceId, deviceName) {
858        this.showOrHide = false;
859        this.selectDevice = 'common/images/ic_hop.svg';
860        var params;
861        console.info('[ttt] AVSessionController[IndexPage] featureAbility.startAbility deviceId=' + deviceId
862        + ' deviceName=' + deviceName);
863        var wantValue = {
864            bundleName:'com.ohos.AVSessionController',
865            abilityName:'com.ohos.AVSessionController.MainAbility',
866            deviceId:deviceId,
867            parameters:params
868        };
869        featureAbility.startAbility({
870            want: wantValue
871        }).then((data) => {
872            console.info('[ttt] AVSessionController[IndexPage] featureAbility.startAbility finished, ' + JSON.stringify(data));
873        });
874        console.info('[ttt] AVSessionController[IndexPage] featureAbility.startAbility want=' + JSON.stringify(wantValue));
875    },
876
877    // 点击收藏按钮
878    onCollectionClick() {
879        if (this.avSessionCtrl == undefined) {
880            return;
881        }
882
883        this.avSessionCtrl.isActive((active) => {
884            if ((active == false) || (active == undefined)) {
885                return;
886            }
887        })
888
889        console.info('[ttt] AVSessionController[IndexPage] onCollectionClick button.');
890        // 发送命令
891        this.avSessionCtrl.sendControlCommand({command: 'toggleFavorite', parameter: "1234567"});
892        this.avSessionCtrl.sendControlCommand({command:'stop'});
893        this.avSessionCtrl.sendControlCommand({command:'fastForward'});
894        this.avSessionCtrl.sendControlCommand({command:'rewind'});
895
896        this.log('sendcontrolcommand success');
897        console.info('sendcontrolcommand success');
898        console.info('[ttt] AVSessionController[IndexPage] onCollectionClick is valid.');
899
900        if (this.collectBtn === 'button_press') {
901            this.collectBtn = 'button_release';
902            console.info('[ttt] AVSessionController[IndexPage] onCollectionClick is button_release.');
903        } else {
904            this.collectBtn = 'button_press';
905            console.info('[ttt] AVSessionController[IndexPage] onCollectionClick is button_press.');
906        }
907    },
908
909    onSetLoopMode(){
910        if (this.avSessionCtrl == undefined) {
911            return;
912        }
913
914        this.avSessionCtrl.isActive((active) => {
915            if ((active == false) || (active == undefined)) {
916                return;
917            }
918        })
919
920        this.loopModIndex ++;
921        if (this.loopModIndex > 3) {
922            this.loopModIndex = 0;
923        }
924        this.SetLoopMode = this.SetLoopIconArray[this.loopModIndex];
925
926        let self = this;
927        this.avSessionCtrl.sendControlCommand({
928            command:'setLoopMode',
929            parameter:this.SetLoopParam[self.loopModIndex]
930        });
931        this.log('sendcontrolcommand success');
932        console.info('sendcontrolcommand success');
933        console.info('[ttt] AVSessionController[IndexPage] onSetLoopMode button.');
934    },
935
936    onSetSpeed() {
937        if (this.avSessionCtrl == undefined) {
938            return;
939        }
940
941        this.avSessionCtrl.isActive((active) => {
942            if ((active == false) || (active == undefined)) {
943                return;
944            }
945        })
946
947        this.SpeedIndex ++;
948        if (this.SpeedIndex > 2) {
949            this.SpeedIndex = 0;
950        }
951        this.SetSpeed = 'x' + this.SetSpeedArray[this.SpeedIndex];
952
953        let self = this;
954        this.avSessionCtrl.sendControlCommand({
955            command:'setSpeed',
956            parameter:self.SpeedIndex
957        });
958        this.log('sendcontrolcommand success');
959        console.info('sendcontrolcommand success');
960        console.info('[ttt] AVSessionController[IndexPage] onSetSpeed button.');
961    },
962
963    onToAbility() {
964
965        if (this.avSessionCtrl == undefined) {
966            return;
967        }
968
969        this.avSessionCtrl.isActive((active) => {
970            if (active == false) {
971                return;
972            }
973        })
974
975        let TriggerInfo = {
976            code:0
977        }
978        this.avSessionCtrl.getLaunchAbility((err,wantAgent1) => {
979            this.log('getLaunchAbility success')
980            this.log(err.code);
981            WantAgent.getBundleName(wantAgent1).then((name) => {
982                console.info('[ttt] AVSessionPlayer[IndexPage] getBundleName bundle name:' + name);
983                this.log('getWantAgent success agent bundle name:' + name);
984            }, e => {
985                this.log(e)
986                console.info('[ttt] AVSessionPlayer[IndexPage] getBundleName error' +  ' is ' + e.message);
987            });
988            wantAgent.trigger(wantAgent1, TriggerInfo,(completeData) => {
989                this.log('completeaData : '+completeData);
990                if(completeData !=undefined){
991                    this.log('getWantAgent success agent completeData:' + completeData.finalCode);
992                }
993
994            })
995        })
996        console.info('[ttt] AVSessionController[IndexPage] onToAbility button.');
997    },
998
999    mediaMusic(e) {
1000
1001        if (this.avSessionCtrl == undefined) {
1002            return;
1003        }
1004
1005        this.avSessionCtrl.isActive((active) => {
1006            if (active == false) {
1007                return;
1008            }
1009        })
1010
1011
1012        this.avSessionCtrl.sendControlCommand({
1013            command:'seek',
1014            parameter:e.value
1015        });
1016        this.log('sendcontrolcommand success');
1017        console.info('sendcontrolcommand success');
1018        console.info('[ttt] AVSessionController[IndexPage] mediaMusic set.' + e.value);
1019
1020    },
1021
1022    ssyave(){
1023        let keyItem = {code:10, pressedTime:123456789, deviceId:0};
1024        let event = {action:2, key:keyItem, keys:[keyItem]};
1025        AVSessionManager.sendSystemAVKeyEvent(event, (err) => {
1026            if (err) {
1027                console.info('AVSessionFrameworkTest: Send System KeyEvent : ERROR : '+err.message);
1028            } else {
1029                this.log('sendSystemAVKeyEvent success');
1030                console.info('AVSessionFrameworkTest: Send System KeyEvent');
1031            }
1032        });
1033    },
1034
1035    // 释放资源
1036    offsessioncreate(){
1037        AVSessionManager.off('sessionCreate');
1038    },
1039
1040    offtopsessionchange(){
1041        AVSessionManager.off('topSessionChange');
1042    },
1043
1044    offmetadataChange(){
1045        this.avSessionCtrl.off('metadataChange');
1046    },
1047
1048    offplaybackstatechange(){
1049        this.avSessionCtrl.off('playbackStateChange');
1050    },
1051
1052    offactivestatechange(){
1053        this.avSessionCtrl.off('activeStateChange');
1054    },
1055
1056    offvalidcommandchange(){
1057        this.avSessionCtrl.off('validCommandChange');
1058    },
1059
1060    destroyde(){
1061        this.avSessionCtrl.destroy();
1062    }
1063}
1064```
1065
1066
1067
1068