How to play audio?

前端 未结 20 3253
抹茶落季
抹茶落季 2020-11-21 13:37

I am making a game with HTML5 and JavaScript.

How could I play game audio via JavaScript?

20条回答
  •  青春惊慌失措
    2020-11-21 14:07

    Add a hidden audio and play it.

    function playSound(url){
      var audio = document.createElement('audio');
      audio.style.display = "none";
      audio.src = url;
      audio.autoplay = true;
      audio.onended = function(){
        audio.remove() //Remove when played.
      };
      document.body.appendChild(audio);
    }
    

提交回复
热议问题