Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play audio?

I am making a game with HTML5 and JavaScript.

How could I play game audio via JavaScript?

like image 758
rshea0 Avatar asked Feb 23 '12 18:02

rshea0


People also ask

How do I play my audio files?

Open File Manager and navigate to the folder where the audio file is located. Drag the audio file icon from File Manager and drop it on the Audio main window. The Selected file is opened. If Automatically play audio file on Open is selected in the Options-Play dialog box, the audio file starts playing.

What program plays audio files?

Google Play Music A unique Android audio player to play audio files on your phone, or stream music files. An audio player for users to on-demand access to over 35 million songs.

How do I play audio files on Android?

Step 1: Firstly, update the music app on your Android smartphone. Step 2: Open the YouTube music app and click on the Settings option. Step 3: In the Settings category, press the 'Library and downloads' option. Step 4: Activate the option 'Show device files' in the library and download option.


2 Answers

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.

like image 33
shanabus Avatar answered Oct 07 '22 09:10

shanabus


If you don't want to mess 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()">Play Audio</button>

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/cc0-audio/t-rex-roar.mp3'],       volume: 0.5,       onend: function () {         alert('Finished!');       }     });     sound.play() </script>
like image 85
Uri Avatar answered Oct 07 '22 08:10

Uri