Playlist with .load ()

0

$("#playlist").load("https://cdn.rawgit.com/lucaskfp/-south-toon-player/master/teste.txt");


function audioPlayer() {
  var currentSong = 0;
  $("#audioPlayer")[0].src = $("#playlist li a")[0];
  $("#audioPlayer")[0].play();
  $("#playlist li a").click(function(e) {
    e.preventDefault();
    $("#audioPlayer")[0].src = this;
    $("#audioPlayer")[0].play();
    $("#playlist li").removeClass("current-song");
    currentSong = $(this).parent().index();
    $(this).parent().addClass("current-song");
  });

  $("#audioPlayer")[0].addEventListener("ended", function() {
    currentSong++;
    if (currentSong == $("#playlist li a").length)
      currentSong = 0;
    $("#playlist li").removeClass("current-song");
    $("#playlist li:eq(" + currentSong + ")").addClass("current-song");
    $("#audioPlayer")[0].src = $("#playlist li a")[currentSong].href;
    $("#audioPlayer")[0].play();
  });
}


// loads the audio player
audioPlayer();
#playlist {
  list-style: none;
}

#playlist li a {
  color: black;
  text-decoration: none;
}

#playlist .current-song a {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><audiosrc="" controls id="audioPlayer">
        Sorry, your browser doesn't support html5!
    </audio>

<ul id="playlist">

</ul>

Note: I need more than one playlist without updating the page, below is the normal working code.

 function audioPlayer(){
            var currentSong = 0;
            $("#audioPlayer")[0].src = $("#playlist li a")[0];
            $("#audioPlayer")[0].play();
            $("#playlist li a").click(function(e){
               e.preventDefault(); 
               $("#audioPlayer")[0].src = this;
               $("#audioPlayer")[0].play();
               $("#playlist li").removeClass("current-song");
                currentSong = $(this).parent().index();
                $(this).parent().addClass("current-song");
            });
            
            $("#audioPlayer")[0].addEventListener("ended", function(){
               currentSong++;
                if(currentSong == $("#playlist li a").length)
                    currentSong = 0;
                $("#playlist li").removeClass("current-song");
                $("#playlist li:eq("+currentSong+")").addClass("current-song");
                $("#audioPlayer")[0].src = $("#playlist li a")[currentSong].href;
                $("#audioPlayer")[0].play();
            });
        }
        

        // loads the audio player
        audioPlayer();
#playlist{
            list-style: none;
        }
        #playlist li a{
            color:black;
            text-decoration: none;
        }
        #playlist .current-song a{
            color:blue;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><audiosrc="" controls id="audioPlayer">
        Sorry, your browser doesn't support html5!
    </audio>
    <ul id="playlist">
         <li class="current-song"><a href="https://ia802705.us.archive.org/22/items/wbt2009-07-24.early_set.flac16/wbt2009-07-24_earlyset_d1t01.mp3">Exit the Premises</a></li>
        <li><a href="https://ia600202.us.archive.org/18/items/ml2005-12-30.sbd.flac16/ml2005-12-30d1t01.mp3">Severe Tire Damage</a></li>
        <li><a href="https://ia801409.us.archive.org/16/items/thc2008-08-15.flac16/thc20080815d1t01.mp3">Broken Reality</a></li>
    </ul>
    
asked by anonymous 30.01.2018 / 21:35

1 answer

0

The .load function will only serve to download content and replace old content.

Another point in your code is that you are giving play before the content of the list is downloaded. Because the .load function is asynchronous, it will run in the background and all the rest of the code will run shortly afterwards. To correct this you must create a callback in the function to give play . Ex:

$("element").load("url", function() {
    /* Play no player */
});

As you want to add more songs, ideally use functions / api such as Ajax , XMLHttpRequest or fetch . They are all the same, so it will depend on which you have the most affinity for. Below is an example with fetch

/* Áudio atual */
let currentSong = 0;

/** 
 * Armazena o player em uma variável. 
 * Isso o ajudará com a manutenção, legibilidade etc.
 */
const player = $("#audioPlayer")[0];

/**
 * Função responsável por carregar as playlist
 */
function loadPlaylist(url) {
  if (url) {
    /* Inicia a requisição e captura o resultado no formato Response. */
    fetch(url).then(response => {

      /* Captura a resposta no formato de texto */
      response.text().then(text => {

        /* Acrescenta o conteúdo na div "#playlist" */
        $(text).appendTo("#playlist");

        /* Verifica se o conteúdo já foi carregado, caso tenha sido ignora o play */
        if ($("#playlist li").length <= 0) {
          player.play();
        } else {
          player.src = $("#playlist li:eq(0) a").attr("href");
          player.play();
        }
      });
    });
  }
}

/**
 * Isso vai ajudar a não ficar adicionando esse código na função "loadPlaylist"
 * Quando ocorrer algum evento de click dentro da div "#playlist", o código
 * vai buscar e verificar se algum deles possui uma função para ser executada.
 */
$("#playlist").on("click", "li a", function(e) {
  e.preventDefault();
  player.src = this;
  player.play();
  $("#playlist li").removeClass("current-song");
  currentSong = $(this).parent().index();
  $(this).parent().addClass("current-song");
});

/**
 * Altera para a próxima música
 * Ps.: Não alterei o código
 */
player.addEventListener("ended", function() {
  currentSong++;
  if (currentSong == $("#playlist li a").length)
    currentSong = 0;

  $("#playlist li").removeClass("current-song");
  $("#playlist li:eq(" + currentSong + ")").addClass("current-song");
  player.src = $("#playlist li a")[currentSong].href;
  player.play();
});

/* Chama a função com a URL */
loadPlaylist("https://cdn.rawgit.com/lucaskfp/-south-toon-player/master/teste.txt");
#playlist {
  list-style: none;
}

#playlist li a {
  color: black;
  text-decoration: none;
}

#playlist .current-song a {
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><audiosrc="" controls id="audioPlayer">
            Sorry, your browser doesn't support html5!
        </audio>

<ul id="playlist"></ul>

<button type="button" onClick="loadPlaylist(prompt('Informe a url'))">Carregar playlist</button>
    
31.01.2018 / 01:06