简体   繁体   English

Angular 2使用“ onended”音频事件发射器和Component本地成员

[英]angular 2 using 'onended' audio event emitter with Component local member

Can anyone help me around with how I use audio.onended() to play next song in the playlist? 有人可以帮助我了解如何使用audio.onended()播放播放列表中的下一首歌吗?
I can add songs to the playlist and even play a song with the above method by passing an audioObject . 我可以通过将audioObject传递给播放列表中的歌曲,甚至可以通过上述方法播放歌曲。 However, when audio.onended fires, it says this.playlist.item is undefined . 但是,当audio.onended触发时,它说this.playlist.item is undefined

It's something to do with the scope I think. 这与我认为的范围有关。
Is there another way around for firing ended() and interact with a member variable of this class? 有没有其他方法可以触发ended()并与此类的成员变量进行交互?

export class ..... {

   playlist = {
       item: []
   };



   playMedia(audioObject) {
       this.nowPlayingChange.next(audioObject);
       if (this.audio) {
           this.audio.src = '';
           this.audio.load();
       }
       this.audio = new Audio();
       this.audio.src = audioObject.src;
       this.audio.type = 'audio/mp3';
       this.audio.load();
       if (!this.audio.error) {
           this.audio.play();
       }
       this.audio.onended = function() {
           if (this.playlist.item.length > 1) {
               for (let i = 0; i < this.playlist.item.length; i++) {
                   if (audioObject.title === this.playlist.item[i].title) {
                       if (i !== (this.playlist.item.length - 1))
                           this.playMedia(this.playlist[i + 1]);
                   } else {
                       this.audio.pause();
                   }
               }
           } else {
               this.audio.pause();
           }
       };
   }
}

use the arrow function => instead of function to preserve this keyword : 使用箭头功能=>而不是function来保留this关键字:

this.audio.onended = () => {         
              if(this.playlist.item.length > 1) {
              for (let i = 0; i < this.playlist.item.length; i++) {
                if (audioObject.title === this.playlist.item[i].title) {
                  if(i !== (this.playlist.item.length - 1))
                  this.playMedia(this.playlist[i+1]);
                } else 
                {
                  this.audio.pause();
                }
              }
            } else {
              this.audio.pause();
            }
            };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM