How to play audio?

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

    Easy with Jquery

    // set audio tags with no preload

    <audio class="my_audio" controls preload="none">
        <source src="audio/my_song.mp3" type="audio/mpeg">
        <source src="audio/my_song.ogg" type="audio/ogg">
    </audio>
    

    // add jquery to load

    $(".my_audio").trigger('load');
    

    // write methods for playing and stopping

    function play_audio(task) {
          if(task == 'play'){
               $(".my_audio").trigger('play');
          }
          if(task == 'stop'){
               $(".my_audio").trigger('pause');
               $(".my_audio").prop("currentTime",0);
          }
     }
    

    // decide how to control audio

    <button onclick="play_audio('play')">PLAY</button>
    <button onclick="play_audio('stop')">STOP</button>
    

    EDIT

    To address @stomy's question, here is how you would use this approach to play a playlist:

    Set your songs in an object:

    playlist = {
        'song_1' : 'audio/splat.mp3',
        'song_2' : 'audio/saw.mp3',
        'song_3' : 'audio/marbles.mp3',
        'song_4' : 'audio/seagulls.mp3',
        'song_5' : 'audio/plane.mp3'
    }
    

    Use the trigger and play functions as before:

    $(".my_audio").trigger('load');
    
    function play_audio(task) {
          if(task == 'play'){
               $(".my_audio").trigger('play');
          }
          if(task == 'stop'){
               $(".my_audio").trigger('pause');
               $(".my_audio").prop("currentTime",0);
          }
     }
    

    Load the first song dynamically:

    keys = Object.keys(playlist);
    $('.my_audio').append("<source id='sound_src' src=" + playlist[keys[0]] + " type='audio/mpeg'>");
    

    Reset the audio source to the next song in the playlist, when the current song ends:

    count = 0; 
    $('.my_audio').on('ended', function() { 
       count++;  
       $("#sound_src").attr("src", playlist[keys[count]])[0];
       $(".my_audio").trigger('load');
       play_audio('play');
    });
    

    See here for an example of this code in action.

    0 讨论(0)
  • 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 )
    
    0 讨论(0)
提交回复
热议问题