Playlist with . load()

Asked

Viewed 119 times

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>

<audio src="" controls id="audioPlayer">
        Sorry, your browser doesn't support html5!
    </audio>

<ul id="playlist">

</ul>

Obs.: need for more than one playlist without updating the page, below is the code that works normal.

 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>

<audio src="" 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>

  • what I wanted was to feed the #playlist with txt files

1 answer

0


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

Another point in your code is that you’re giving play before the contents of the list are downloaded. As the function .load is asynchronous, it will run in the background and all the rest of the code will run soon after. To fix this you must create a callback in the function to give the play. Ex:

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

As you want to add more songs, the ideal is to use functions/api as for example Ajax, XMLHttpRequest or fetch. They’re all the same, so it depends on which you have the most affinity. 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>

<audio src="" 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>

  • Thank you very much for the explanation, actually the goal was to replace even the content of the playlist but without changing the audio that is currently playing. Type would be a menu with Playlist 1, Playlist 2, Playlist 3 that the user could switch without influencing the player, until this part of switching playlists was working well but the script of playing on the player that stopped working.

  • @Lucaskennedy you want to have several playlists, however, working on the same player?

  • Yes, let’s say I have another <ul id="lists"> and in <li><a> I would have my list1.txt , Lista2.txt , list3.txt start it in list 1 and then the user could switch the view between the lists without restarting or stop the song that would be playing currently

  • Opa brother got what I wanted, I made the changes, thank you very much for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.