Home  >  Q&A  >  body text

Learn how to play audio

<p>I'm making a game using HTML5 and JavaScript. </p> <p>How do I play game audio via JavaScript? </p>
P粉760675452P粉760675452446 days ago619

reply all(2)I'll reply

  • P粉635509719

    P粉6355097192023-08-22 09:50:53

    It's easy, just get your audio element and call the play() method:

    document.getElementById('yourAudioTag').play();

    Check out this example: http://www.storiesinflight.com/html5/audio.html

    This site reveals some other cool things like load(), pause() and audio elements some other attributes.

    reply
    0
  • P粉512729862

    P粉5127298622023-08-22 09:12:54

    If you don't want to deal with HTML elements:

    var audio = new Audio('audio_file.mp3');
    audio.play();
    

    function play() {
      var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
      audio.play();
    }
    <button onclick="play()">播放音频</button>

    reply
    0
  • Cancelreply