angular 2使用'onended'音频事件发射器和Component local成员

时间:2017-10-16 15:20:43

标签: javascript html angular audio

有人可以帮助我使用audio.onended()播放播放列表中的下一首歌吗? 我可以通过传递audioObject将歌曲添加到播放列表中,甚至可以使用上述方法播放歌曲。但是,当audio.onended触发时,会显示this.playlist.item is undefined

这与我认为的范围有关 是否还有另一种解决方法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();
           }
       };
   }
}

1 个答案:

答案 0 :(得分:1)

使用箭头功能=>代替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();
            }
            };