Jump to content
MakeWebGames

Playing a soundtrack in your game


runthis

Recommended Posts

So since I run an online hacking game focused on "Uplink" nostalgia, I needed music, now this is obviously something you want to give a user control over and should not be something you added to be "generous" as most users might find what you consider to be "music" annoying. However this, with help of html5 will get you on the right path to getting a soundtrack going.

This code will play 5 tracks assuming they are named track1 - track5 ogg or mp3 (it is recommended you have both for browser compatibility) and is playing them from a folder named "sounds" and when finished with track5 (last track), it will loop back to track1.

 

var snd; //declare this so you can create options in other parts of your game later to pause songs, change volume, etc.
 function music(track) {
   if (window.HTMLAudioElement) {
     snd = new Audio('');
     if(snd.canPlayType('audio/ogg')) {
       snd = new Audio('sounds/' + track + '.ogg');
     }
     else if(snd.canPlayType('audio/mp3')) {
       snd = new Audio('sounds/' + track + '.mp3');
     }
     snd.volume=.60; // 60 percent is a good way to be less obtrusive
     snd.play();
     if(track == 'track1'){
      snd.addEventListener('ended', function() { music('track2'); }, false);
     }
     if(track == 'track2'){
      snd.addEventListener('ended', function() { music('track3'); }, false);
     }
     if(track == 'track3'){
      snd.addEventListener('ended', function() { music('track4'); }, false);
     }
     if(track == 'track4'){
      snd.addEventListener('ended', function() { music('track5'); }, false);
     }
     if(track == 'track5'){
      snd.addEventListener('ended', function() { music('track1'); }, false);
     }
   }
   else { }
 }

 

 

Usage example

 

  music('track1');

 

Some usage examples that can be programmed with a bit of javascript to a slider to change volume or tied to a onclick event

 

snd.volume="1.0"; // Maximum
snd.volume="0.1"; // Pretty low
snd.muted = true; // Mute
snd.pause();  // Pause music
snd.play(); // Play music 

 

Demo

Wont be available when my new game is released.

http://www.purevirus.com/demo

Edited by runthis
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...