简体   繁体   中英

Javascript audiofile “previous/next” file/song skipping functionality?

I have created a simple music player.

Play, pause, and stop all work as expected.

But, I can't figure out how to make a function skip forward or backwards from file to file.

JS:

This is support code for the rest of the widget.

  var songs = ["violin", "stronger", "boom"]
  var songIndex = 1;
  var currentSong = new Audio("music/" + songs[songIndex] + ".mp3")
  $scope.playStatus = true;

This simply toggles play vs pause:

  $scope.playPause = function() {
    if (!$scope.playStatus) currentSong.pause();
    else currentSong.play();
    $scope.playStatus = !$scope.playStatus;
  }

This fully stops the song and returns it to the beginning:

  $scope.stopSong = function() {
    currentSong.pause();
    currentSong.currentTime = 0;
    $scope.playStatus = true;
  }

This is where I attempt to create "previous song" functionality:

  $scope.previousSong = function() {
    currentSong.pause()
    if (songIndex === 0) {
      songIndex = songs.length;
    } else {
      songIndex -= 1;
    }
    currentSong.play()
    $scope.playStatus = true;
  }

This last function is where I expected the simplest logic.

Pause the song, move backwards one index in the array of songs, then play. Yet, it simply continues to play the same song. No errors given.

This is because you are not loading the correct mp3. Try something like

  $scope.previousSong = function() {
    currentSong.pause()
    if (songIndex === 0) {
      songIndex = songs.length - 1;
    } else {
      songIndex -= 1;
    }
    currentSong = new Audio("music/" + songs[songIndex] + ".mp3"); // reload the new song
    currentSong.play();
    $scope.playStatus = true;
  }

I found two errors in your code:

  • var songIndex = 1 should be var songIndex = 0 (you want to start at the first)
  • songIndex = songs.length; should be songIndex = songs.length - 1; (the index equal to the length of the array is out of bounds)

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