Last active
October 31, 2019 14:53
-
-
Save heylastway/c03d76d9cb3b34504c74af9c2bbc22e8 to your computer and use it in GitHub Desktop.
How to preload a sound in Javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Audio preloader | |
$(window).ready(function(){ | |
var audio_preload = 0; | |
function launchApp(launch){ | |
audio_preload++; | |
if ( audio_preload == 3 || launch == 1) { // set 3 to # of your files | |
start(); // set this function to your start function | |
} | |
} | |
var support = {}; | |
function audioSupport() { | |
var a = document.createElement('audio'); | |
var ogg = !!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, '')); | |
if (ogg) return 'ogg'; | |
var mp3 = !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, '')); | |
if (mp3) return 'mp3'; | |
else return 0; | |
} | |
support.audio = audioSupport(); | |
function loadAudio(url, vol){ | |
var audio = new Audio(); | |
audio.src = url; | |
audio.preload = "auto"; | |
audio.volume = vol; | |
$(audio).on("loadeddata", launchApp); // jQuery checking | |
return audio; | |
} | |
if (support.audio === 'ogg') { | |
var snd1 = loadAudio("sounds/sound1.ogg", 1); // ie) the 1 is 100% volume | |
var snd2 = loadAudio("sounds/sound2.ogg", 0.3); // ie) the 0.3 is 30% | |
var snd3 = loadAudio("sounds/sound3.ogg", 0.05); | |
// add more sounds here | |
} else if (support.audio === 'mp3') { | |
var snd1 = loadAudio("sounds/sound1.mp3", 1); | |
var snd2 = loadAudio("sounds/sound2.mp3", 0.3); | |
var snd3 = loadAudio("sounds/sound3.mp3", 0.05); | |
// add more sounds here | |
} else { | |
launchApp(1); // launch app without audio | |
} | |
// this is your first function you want to start after audio is preloaded: | |
function start(){ | |
if (support.audio) snd1.play(); // this is how you play sounds | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment