How to play audio?

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

    
    

    // 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

    
    
    

    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("");
    

    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.

提交回复
热议问题