简体   繁体   中英

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?
I can add songs to the playlist and even play a song with the above method by passing an audioObject . However, when audio.onended fires, it says 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?

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 :

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();
            }
            };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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