javascript - 如何使音频仅在添加到播放列表时播放?

标签 javascript jquery html

如果您运行代码并转到第一首歌曲的末尾,您会发现它会自动转到下一首歌曲。我只希望它在单击“添加到播放列表”按钮时转到下一首歌曲,如果未单击它,我希望它直接跳过它。有人请帮助我,我将不胜感激

$(document).ready(function() {
  $(".toggle_container").hide();
  $("button.reveal").click(function() {
    $(this).toggleClass("active").next().slideToggle("fast");

    if ($.trim($(this).text()) === 'Add to Playlist') {
      $(this).text('Remove from playlist');
    } else {
      $("#audioPlayer")[0].pause();
      $("#audioPlayer")[0].currentTime = 0;
      $(this).text('Add to Playlist');
    }

    return false;
  });
  $("a[href='" + window.location.hash + "']").parent(".reveal").click();
});
#searchbar {
  padding: 15px;
  border-radius: 10px;
  width: 80%
}

#playlist .current-song a {
  color: #7777FE;
  border-color: #008ae6;
}

#playlist {
  list-style: none;
}

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


#playlist {
  font-size: 14.5px;
  list-style: none;
  margin-left: 40px;
  color: blue;
}

.animals {
  display: list-item;
  margin-bottom: 5px;

}

#background {
  border: solid;
  width: 100%;
  height: 75px;
  margin-top: 5px;
  margin-left: 5px;
}

#background2 {
  border: solid;
  width: 98%;
  height: 75px;
  margin-top: 5px;
  margin-left: 5px;
}

#background3 {
  border: solid;
  width: 100%;
  height: 75px;
  margin-top: 5px;
  margin-left: 0px;
}


#playlist.current-song {
  border-color: #008ae6;
}

.image {
  width: 100px;
  float: left
}

#song {
  margin-left: 13px;
  margin-top: 9px;
  float: left;
}

.artist {
  text-align: center;
  margin-right: 20px;
  font-size: 12px;
  margin-top: 14px;
}

.image3 {
  width: 100px;
  float: left;
  height: 75px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <audio id="audioPlayer" preload="true" controls="true">
    </audio>
    <ul id="playlist">
    <li class="animals"><a href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/355309/Swing_Jazz_Drum.mp3"><div id="background3"><img src="https://images.unsplash.com/photo-1575489560633-6a7609328e67?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ" class="image3"/><h4 id="song">Freedom Reign</h4><h5 class="artist">Abt Goat</h5></div></a></li>

      <button class="reveal">Add to Playlist </button>
      <div class="toggle_container">
        <div class="block">
          <li class="current-song"><a href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/355309/Swing_Jazz_Drum.mp3">
              <div id="background2"><img src="https://images.unsplash.com/photo-1577044685231-70e99274404c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1567&q=80Cat" class="image" />
                <h4 id="song">Tummy Why</h4>
                <h5 class="artist">Revy Conover</h5>
              </div>
            </a></li>
        </div>
      </div>
    </ul>
    <script>
      audioPlayer();

      function audioPlayer() {
        var currentSong = 0;
        $("#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();
        });
      }

    </script>

最佳答案

给你,我做了很多改变。

制作播放列表的最佳方法是使用数组制作列表!

现在....

  • 第一首歌曲将不断重复,直到添加新歌曲
  • 如果添加第二首歌曲,它将一首接一首地重复。
  • 您可以添加歌曲并删除它们(如果删除的歌曲正在播放,它将自动跳到嵌套歌曲。
  • 您可以通过点击添加的“您的播放列表”中的歌曲详细信息框来播放任何歌曲。

希望您喜欢这个修改。

var APlayer = $('audio#audioPlayer')[0];
var AP_PlayList = [];
var currentTrack = 0;

// play clicking a Song in YourPlaylist
$('body').on("click", '.AudioSong', function(e) {
  var trackID = $(this).attr('id');
  index = AP_PlayList.findIndex(x => x.id === trackID);
  console.log(index + "::" + trackID);
  audioPlayer(index);
});

// in the end of each song load next song in the arraylist and play
$('#audioPlayer').on('ended', function() {
  NextSong();
});

function audioPlayer(TrackNum){
  var APlayer = $('audio#audioPlayer')[0];  // Get AudioPlayer element
  APlayer.setAttribute("trackid", AP_PlayList[TrackNum]['id']);  //set Current Playing song TrackID to player
  APlayer.setAttribute("src", AP_PlayList[TrackNum]['link']);  //set Current Playing song Link/Path to player
  console.log("Started Track " + AP_PlayList[TrackNum]['id']);
  APlayer.loop = false;  // Set Player not to loop songs. so $('#audioPlayer').on('ended', function can be detected
  APlayer.load();  // Load player and play the song set
  // NowPlaying song in YourPlaylist
  $('span#nowplaying').html("&nbsp;");  // Clear all NowPlaying
  $('#your_playlist div#list').find('div#'+ AP_PlayList[TrackNum]['id'] + ' span#nowplaying').html(" &#8250; Now Playing");  // Set NowPlaying to current playing song
}

function NextSong(){
  var APlayer = $('audio#audioPlayer')[0];
  // Check Array song list lenght
  if (AP_PlayList.length > 0) {  // if songs exisxt in array list 
    console.log("Ended Track " + AP_PlayList[currentTrack]['id']);
    currentTrack++; // get next song's track number
    if(currentTrack > AP_PlayList.length-1) { currentTrack = 0 } // loop the playlist if it last song
    audioPlayer(currentTrack); // play next song
  } else { // if songs array list is empty
    $('#your_playlist div#list div').remove();	// Clean the YourPlaylist 
    $('small#nosongs').fadeIn();	// Show No Songs massage in YourPlaylist
    APlayer.pause();	// Stop current playing song
    APlayer.setAttribute("src", ''); // Remove current playing song from player
    APlayer.load(); // Reload Player
  }
}

// When Remove from Playlist Button Clicked
$('body').on("click", '.removetrack', function(e) {
  var TrackID = $(this).attr('data-id');
  // Remove the song from Array songlist
  $.each(AP_PlayList, function(i, el){
    if (this.id == TrackID){
      AP_PlayList.splice(i, 1);
    }
  });
  //Chk if the removed song is playing
  var APlayer = $('audio#audioPlayer')[0];
  var PlayingTrackID = APlayer.getAttribute("trackid");
  if (PlayingTrackID === TrackID) { 
    NextSong(); // if the removed song is playing skip to next song
  }
  $('#your_playlist div#list div#' + TrackID).remove();  // remove the song from "YourPlaylist"
  $('.addtrack.'+TrackID).fadeIn();  //  Show Add to playlist Button
  $('.removetrack.'+TrackID).fadeOut();  // Hide Remove from playlist Button
});

// When Add to Playlist Button Clicked
$('body').on("click", '.addtrack', function(e) {
  e.preventDefault();
  var TrackID = $(this).attr('data-id');
  var TrackLink = $(this).attr('data-src');
  // check if array is empty
  if (AP_PlayList.length > 0) { // if not empty
    // get the object form the array songlist that macht TrackID
    var emps = $.grep(AP_PlayList, function(n, i) {
      return n.id === TrackID;
    });
    if (emps.length == 0 || emps[0].id != TrackID) { // if song is not in array songlist then add this song to array songlist
      AP_PlayList.push({
        id: TrackID,
        link: TrackLink
      });
      updateHTMLlist(); // add new song and update YourPlaylist
    }
  } else {  // if array is blank then add this song to array list
    AP_PlayList.push({
      id: TrackID, 
      link:  TrackLink
    });
    updateHTMLlist(); // add new song and update YourPlaylist
  }			
  console.log(AP_PlayList);
  function updateHTMLlist() {
    // Creating Selected YourPlaylist Part
    var getSongDetails = $("ul").find(`[data-trackID='${TrackID}']`).html(); // get songs info from UL list item
    $('small#nosongs').fadeOut();
    $('#your_playlist div#list').append('<div class="AudioSong" id="' + TrackID + '">' + getSongDetails + '</div>');
    $('<button class="removetrack active" data-id="'+ TrackID +'">Remove from Playlist</button>').appendTo('div#'+ TrackID);

  }
  //Load player if its not playing 
  if (APlayer.paused) {
    audioPlayer(0);
  }
  $(this).parent().find('.removetrack').fadeIn(); // Show Remove from playlist Button
  $(this).fadeOut(); // Hide Add to playlist Button
});
#searchbar {
  padding: 15px;
  border-radius: 10px;
  width: 80%
}

#playlist .current-song a {
  color: #7777FE;
  border-color: #008ae6;
}

#playlist {
  list-style: none;
}

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

#playlist {
  font-size: 14.5px;
  list-style: none;
  margin-left: 40px;
  color: blue;
}

.animals {
  display: list-item;
  margin-bottom: 5px;
}

#background {
  border: solid;
  width: 100%;
  height: 75px;
  margin-top: 5px;
  margin-left: 5px;
}

#background2 {
  border: solid;
  width: 100%;
  height: 100px;
  margin-top: 5px;
}

#background3 {
  border: solid;
  width: 100%;
  height: 100px;
  margin-top: 5px;
}

div#your_playlist {
  background-color: rgba(239,239,239,0.68);
}

div#your_playlist .AudioSong{
  padding: 5px;
  display: inline-block;
  border: 2px solid rgba(39,200,184,0.79);
  width: 300px;
}

div#your_playlist .AudioSong:hover{
  border: 2px solid rgba(255,176,5,1.00);
  cursor: pointer;
}

#playlist.current-song {
  border-color: #008ae6;
}

.image {
  width: auto;
  height: 100px;
  float: left;
  padding-right: 5px;
}

#song {
  margin: 0;
  text-align: left;
}

.artist {
  margin: 0;
  padding: 5px;
  text-align: left;
  font-size: 12px;
}

.image3 {
  width: 100px;
  float: left;
  height: 75px;
}

button.removetrack{
  display: none;
}

button.active{
  display: block;
  opacity: 1;
  visibility: visible;
}

#nowplaying{
  animation:blinkingText 0.5s infinite;
  font-size: 12px;
  font-weight: bold;
}
@keyframes blinkingText{
  0%{     color: rgba(0,0,0,0.00); }
  25%{    color: rgba(0,0,0,0.25); }
  50%{    color: rgba(0,0,0,0.50); }
  75%{    color: rgba(0,0,0,0.75); }
  100%{   color: rgba(0,0,0,1.00); }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio style="width: 100%" id="audioPlayer" preload="true" controls="true" autoplay></audio>
    <div id="your_playlist">
    	<h3>Your Playlist</h3>
    	<div id="list">
    		<small id="nosongs">No Songs found ! Add songs to playlist,<br></small>
    	</div>
    </div>
    
    <hr>
    <h3>Avaibale Song List</h3>
    <ul id="playlist">
	    <li class="track" id="track1">
			<div id="background3" class="background" data-trackID="1">
				<img src="https://images.unsplash.com/photo-1575489560633-6a7609328e67?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ" class="image"/>
				<h4 id="song">&nbsp;Freedom Reign</h4>
				<h5 class="artist">&nbsp;Abt Goat</h5>
				<span id="nowplaying">&nbsp;</span>
			</div>
			<button class="addtrack 1" data-id="1" data-src="https://archive.org/download/slac2002-02-15/slac2002-02-15d1t07_64kb.mp3">Add to Playlist</button>
			<button class="removetrack 1" data-id="1">Remove from Playlist</button>
      	</li>
		<li class="track" id="track2">
			<div id="background2" class="background" data-trackID="2">
				<img src="https://images.unsplash.com/photo-1577044685231-70e99274404c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1567&q=80Cat" class="image" />
				<h4 id="song">&nbsp;Tummy Why</h4>
				<h5 class="artist">&nbsp;Revy Conover</h5>
				<span id="nowplaying">&nbsp;</span>
			</div>
			<button class="addtrack 2" data-id="2" data-src="https://archive.org/download/ra2007-07-21/ra2007-07-21d1t05_64kb.mp3">Add to Playlist</button>
			<button class="removetrack 2" data-id="2">Remove from Playlist</button>
		</li>
    </ul>

关于javascript - 如何使音频仅在添加到播放列表时播放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59572468/

相关文章:

javascript - Jquery 中的简单测试不起作用。绿色方 block 不显示

javascript - 当您从 anchor 标记开始时,JQuery-Mobile 滑动不起作用

javascript - 如何在网络浏览器上通过 Live555 服务器的 rtsp 协议(protocol)流式传输视频

javascript - 使用 Javascript 触发基本的 CSS 动画

java - 如何在android中下载页面

javascript - 使用 Three.js 如何沿指定平面移动对象?

jQuery 使用 fullcalendar 插件获取下个月的数据

javascript - $.each 函数显示每个 DIV,一次一个

html - CSS 字体图像

javascript - 尽管点击了模态框仍保持打开状态