JavaScript audio not playing outside of jQuery function
        Posted  
        
            by 
                user1814016
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by user1814016
        
        
        
        Published on 2012-11-25T22:09:04Z
        Indexed on 
            2012/11/25
            23:04 UTC
        
        
        Read the original article
        Hit count: 263
        
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!');
    }
  }
© Stack Overflow or respective owner