JavaScript audio not playing outside of jQuery function
- by user1814016
I know the question title doesn't make much sense, but I can't think of a better way to put it. I am a newbie to jQuery and I'm using this code to fade in a <div> and play a sound:
$(document).ready(function(){
$('#speech').fadeIn('medium', function() {
play('msg_appear');
var sptx = $('<p class="stext">').text('There is nothing here.');
$('#speech').append(sptx);
$('.stext').typeOut({marker: '', delay: 22});
});
});
This code runs fine however the sound plays after the fade-in is complete. I wanted it to play while it was fading in, so I tried placing the play() call outside of the fade-in function like this:
$(document).ready(function(){
play('msg_appear');
$('#speech').fadeIn('medium', function() {
However, now it's not playing at all. There's no errors on the JavaScript console so I'm unsure if it's a syntax error, and probably something obvious, but I don't know what.
play() is a function I found to play audio, here it is if it matters at all. I placed it in the same file the above code is; right above the $(document).ready().
function play(sound) {
if (window.HTMLAudioElement) {
var snd = new Audio('');
if(snd.canPlayType('audio/ogg')) {
snd = new Audio(sound + '.ogg');
}
else if(snd.canPlayType('audio/mp3')) {
snd = new Audio(sound + '.mp3');
}
snd.play();
}
else {
alert('HTML5 Audio is not supported by your browser!');
}
}