How to play audio?

前端 未结 20 3191
抹茶落季
抹茶落季 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 13:54

    If you are getting the following error:

    Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

    That means the user needs to interact with the website first (as the error message says). In this case you need to use click or just another event listener, so the user can interact with your website.

    If you want to auto load the audio and don't want the user to interact with the document first, you could use setTimeout.

    setTimeout(() => {
      document.getElementById('mySound').play();
    }, 500)

    The sound will start after 0.5 second.

提交回复
热议问题