使用JavaScript创建音乐播放器

时间:2018-11-15 23:49:41

标签: javascript jquery

我正在尝试创建音乐播放器。 我的HTML代码是:

<div id="main">
       <div id="list"  draggable="true">

       </div>

       <div id="player">
         <div id="buttons">

           <button id="pre" onclick="pre()"><img src="images/pre.png" height="90%" width="90%"></button>
           <button id="play" onclick="playAudio()"><img src="images/play.png" height="90%" width="90%"></button>
           <button id="next" onclick=" next()"><img src="images/next.png" height="90%" width="90%"></button>
           <input type="file" id="file" name="file" multiple ="multiple" style=" display : none ;">
           <button id="browse"><img src="images/browse.jpg" height="90%" width="90%"></button>
           <button id="unmute"><img src="images/unmute.png" height="90%" width="90%"></button>

         </div>
         <div id="seekbar">
           <div id="fill"></div>
           <div id="handle"></div>
         </div>
       </div>

     </div> 

我的JavaScrpit是:

// Browse button
      $("#browse").on("click", function() {
              $("input").trigger("click");
       });

    // Append the music   
      $("#file").change(function() {
      var result = $(this)[0].files;
      for(var i = 0 ; i< result.length ; i++){
       var file = result[i];
       // here are the files
         $("#list").append("<p id='first'>" + file.name + " (TYPE: " + file.type + ", SIZE: " + file.size + " ) </p>");  

    }
    });

    // play the music

    $("#list").on( "click" , "#first" , function(){
        console.log(song );

    });


var songs = document.getElementById("list") ;

var song = new Audio();
var currentSong = 0 ;

$("#list").on( "click" , "#first" , function(){
        playSong();
        });

 window.onload = playSong ;

function playSong(){ 
    song.src = songs[currentSong];

    song.play();
};

我想将音乐追加到(带有id = list的div)上,然后当我单击音乐时播放它,但无法正常工作,并给我这个错误:: Uncaught(promise)DOMException:无法加载,因为找不到支持的来源。

有人可以帮助我吗????

1 个答案:

答案 0 :(得分:0)

归档实际描述的最佳方法是将音频URL放入数组中。就像下面的代码一样:

let song_list = new Array(); // Contains Audio URLs 
let current_song = 0;
let player = new Audio();
player.src = song_list[current_song];

function playSong(){
    player.play();
}

function pauseSong(){
    player.pause();
}

function nextSong(){
    player.pause();
    player.src = song_list[++current_song];
    player.onload = ()=>{
          player.play(); 
    };
}

请记住,自动播放无法正常工作。您至少需要与网站进行交互才能实际听到音频(至少在Google Chrome上,或者在所有运行V8的浏览器上更清晰)。