Playing audio with Javascript?

Playing audio with Javascript?

I am making a game with HTML5 and Javascript.
How could I play game audio via Javascript?

Solutions/Answers:

Solution 1:

If you don’t want to mess with 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 uses the HTMLAudioElement interface, which plays audio the same way as the <audio> element.


If you need more functionality, I used the howler.js library and found it simple and useful.

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

Solution 2:

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 uncovers some of the other cool things you can do such as load(), pause(), and a few other properties of the audio element.

Solution 3:

http://www.schillmania.com/projects/soundmanager2/

SoundManager 2 provides a easy to use API that allows sound to be played in any modern browser, including IE 6+. If the browser doesn’t support HTML5, then it gets help from flash. If you want stricly HTML5 and no flash, there’s a setting for that, preferFlash=false

It supports 100% Flash-free audio on iPad, iPhone (iOS4) and other HTML5-enabled devices + browsers

Use is as simple as:

<script src="soundmanager2.js"></script>
<script>
    // where to find flash SWFs, if needed...
    soundManager.url = '/path/to/swf-files/';

    soundManager.onready(function() {
        soundManager.createSound({
            id: 'mySound',
            url: '/path/to/an.mp3'
        });

        // ...and play it
        soundManager.play('mySound');
    });
</script>

Here’s a demo of it in action: http://www.schillmania.com/projects/soundmanager2/demo/christmas-lights/

Solution 4:

This is a quite old question but I wanna add some useful info. The topic starter has mentioned that he is "making a game". So for everybody who needs audio for game development there is a better choice than just an <audio> tag or an HTMLAudioElement. I think you should consider the use of the Web Audio API:

While audio on the web no longer requires a plugin, the audio tag brings significant limitations for implementing sophisticated games and interactive applications. The Web Audio API is a high-level JavaScript API for processing and synthesizing audio in web applications. The goal of this API is to include capabilities found in modern game audio engines and some of the mixing, processing, and filtering tasks that are found in modern desktop audio production applications.

Solution 5:

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.

Solution 6:

Add a 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);
}