我的自动点唱机应用程序在循环播放所有歌曲后中断

时间:2017-07-24 15:01:17

标签: javascript

在浏览播放列表中的所有歌曲后,我的点唱机应用程序无法重新开始。相反,它会一起停止功能。到目前为止,它会播放,暂停,停止,返回和接下来。第二首它贯穿了最后一首歌,然后我点击了#34; next"什么都没有发生,其他功能也没有用。

Jukebox.prototype.next = function() {
  this.jamz[index].pause();
  index++
  this.jamz[index].currentTime = 0;
  this.jamz[index].play();
  if (index == this.jamz.length) {
    this.jamz[index].currentTime = 0;
    this.jamz[index].play();
  }
}

Jukebox.prototype.back = function() {
  this.jamz[index].pause();
  index--
  this.jamz[index].currentTime = 0;
  this.jamz[index].play();
  if (index == 0) {
    this.jamz[index].currentTime = 0;
    this.jamz[index].play();
  }
}

这是完美运行的代码,直到它到达最后一首歌的结尾。我试着让它回到我的jamz阵列中的第一首歌曲,里面有我所有的音乐。

我的控制台中的错误似乎是;

未捕获的TypeError:无法设置属性' currentTime'未定义的     在Jukebox.next(script.js:55)

4 个答案:

答案 0 :(得分:1)

您可以尝试重新排序代码以检查您是否已经到达播放列表的末尾 - 否则您将收到javascript错误并且它将停止您的程序,即:

Jukebox.prototype.next = function() {
    this.jamz[index].pause();
    if (index == this.jamz.length-1) {
        index=0;
    } else {
        index++;
    }
    this.jamz[index].currentTime = 0;
    this.jamz[index].play();  
}

Jukebox.prototype.back = function() {
    this.jamz[index].pause();
    if (index == 0) {
        // rotate back from first track to last track
        index = this.jamz.length-1;  
    } else {
        index--;
    }
    this.jamz[index].currentTime = 0;
    this.jamz[index].play();  
}

答案 1 :(得分:0)

我认为在调用this.jamz [index] .play()

之前,你必须检查索引是否超出0到jamz.length - 1的范围。

答案 2 :(得分:0)

js中的列表为0索引,这表示列表中的最后一项具有索引list.length-1
在您的情况下,您需要将index == this.jamz.length更改为index == this.jamz.length-1。此外,对于良好的测量,如果可以提供帮助,则不应使用==。 js中的==运算符与其他语言中的==运算符不同。您想使用===运算符。

Jukebox.prototype.next = function() {
  this.jamz[index].pause();
  index++
  this.jamz[index].currentTime = 0;
  this.jamz[index].play();
  if (index === this.jamz.length-1) {
    this.jamz[index].currentTime = 0;
    this.jamz[index].play();
  }
}

Jukebox.prototype.back = function() {
  this.jamz[index].pause();
  index--
  this.jamz[index].currentTime = 0;
  this.jamz[index].play();
  if (index === 0) {
    this.jamz[index].currentTime = 0;
    this.jamz[index].play();
  }
}

答案 3 :(得分:0)

你超过了数组的长度,并且当它到达播放列表的末尾时你不能设置下一首歌。

Jukebox.prototype.next = function() {
  this.jamz[index].pause();
  this.jamz[index].currentTime = 0;

  //Check if you are at the end of your playlist
  if (index === this.jamz.length - 1) {
    index = 0;
  }else{
    index++;
  }
  this.jamz[index].currentTime = 0;
  this.jamz[index].play();
}