How to play audio?

前端 未结 20 3483
抹茶落季
抹茶落季 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:45

    With the security requirements that a user must interact with a webpage for audio to be allowed this is how I do it, based on reading many articles, including on this site

    1. Define the required audio files in your html
    2. Have a start game button with an onclick
    3. When the button is clicked then play and pause ALL the audio files bar the one you want to play at the beginning

    Because all the audio files have been "played" on the same OnClick, you can now play them any time in the game without restrictions

    Note that for best compatability do not use wav files, MS do not support them

    Use mp3 and ogg, that covers all devices

    Example:

    
    

    repeat as needed for all audio in the game

    Then:

    document.getElementById("welcome").play();
    document.getElementById("welcome").pause();
    

    repeat as needed except do not pause the audio you want to hear when the game starts

提交回复
热议问题