How to play audio?

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

    I had some issues with playing audio, especially since Chrome has updated that the user has to interact with the document first.

    However, across almost all solutions I found is that the JS code has to actively set listeners (e.g. button clicks) to receive user events in order to play the audio.

    In my case I just wanted my game to play BGM as soon as the player interacts with it, so I made myself a simple listener that keeps checking whether the web page is being interacted or not.

    const stopAttempt = setInterval(() => {
        const audio = new Audio('your_audio_url_or_file_name.mp3');
        const playPromise = audio.play();
        if (playPromise) {
          playPromise.then(() => {
            clearInterval(stopAttempt)
          }).catch(e=>{
            console.log('' + e);
          })
        }
    }, 100 )
    

提交回复
热议问题