Play audio using Javascript?

Keywords: Javascript JQuery html5 network

I'm making games with HTML5 and Javascript.

How to play game audio through Javascript?

#1 building

If you don't want to clutter HTML elements:

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

var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3'); audio.play();

This use HTMLAudioElement Interface, which plays audio in the same way as < audio > same element .

If I need more features, I use howler.js Library, found it simple and practical.

<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.1/howler.min.js"></script> <script> var sound = new Howl({ src: ['https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3'], volume: 0.5, onend: function () { alert('Finished!'); } }); sound.play() </script>

#2 building

This is a very old problem, but I want to add some useful information. The topic entrant mentioned that he was "making a game". Therefore, for everyone who needs audio for game development, there is a better choice than the < audio > tag or HTML audioelement. I think you should consider using Web Audio API :

Although plug-ins are no longer needed for network audio, audio tagging brings obvious limitations for complex games and interactive applications. The Web Audio API is an advanced JavaScript API for processing and compositing audio in Web applications. The goal of the API is to include functions in the modern game audio engine and some mixing, processing and filtering tasks in the modern desktop audio production application.

#3 building

Easy to use jQuery

//Set audio label without 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 play and stop methods

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 the audio

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

edit

To solve @ stomy's problem, this is how to play playlists in this way:

Set songs in one 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'>");

At the end of the current song, reset the audio source to the next song in the playlist:

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

Please see here To get an actual example of this code.

#4 building

I play the sound this way

var audioElement;
if(!audioElement) {
  audioElement = document.createElement('audio');
  audioElement.innerHTML = '<source src="' + '/audio/sound.mp3'+ '" type="audio/mpeg" />'
}
audioElement.play();

#5 building

Add hidden audio and play it.

function playSound(url){
  var audio = document.createElement('audio');
  audio.style.display = "none";
  audio.src = url;
  audio.autoplay = true;
  audio.onended = function(){
    audio.remove() //Remove when played.
  };
  document.body.appendChild(audio);
}

Posted by coderWil on Mon, 06 Jan 2020 05:29:44 -0800