javascripthtmlcss

playing audio when page opened


Hi all iam trying to play audio when page opened or launched i have used window.onload but the audio still not playing although it's playin on blur and focus

I have tried window.onload <body onload> to play the audio once launched but not playing also the alert is popingup but the sound not working

 window.onload = function() {
            // This function will be executed when the page finishes loading
          birdAudio.play();
            alert('The page has finished loading!');
        };

Solution

  • I don't think you need javascript to do this as HTML 5 has a built in audio system as such :

    <audio controls autoplay mute>
        <source src="audio_file.mp3" type="audio/mpeg">
    </audio>
    

    You could remove the autoplay command from the first line to NOT make it automatically play just so you are aware. With the controls command, they can click to play it if they decide to do that, instead of forcing them to listen to it each and everytime the page loads.

    But you could put something like this in, and just replace the link to the mp3 file you wish to play on page load. If it is in the same directory as the html file, it should just play, however if you have directory nesting or offsite files, make sure you have the proper rights to those locations if you find problems getting them to play.

    Although, similar as has been mentioned by others, its not best practice to play an audio file automatically on page load. Perhaps you should build an options tab to let them click to turn it on if they make the concious choice to want to listen to it automatically everytime.

    UPDATE - as per @h0r53 's suggestion, add the mute command after autoplay so that it will give the user an option to unmute to play if they wish.