Using the standard gamePad code, not finding sound files even though the path name is correct?

71 views Asked by At

Using the standard gamePad code, not finding sound files even though the path name is correct?

I have definitely researched this question. For sure, I have found code on SO claiming to solve this dilemma, but this published code doesn't.

I am successfully finding the sound file using Preview under BBEdit's "Markup" Menu. But, the oh-oh surfaces when running my game on my commercial Server.

I am even successful when using keypress code is activated -- local on my Mac and on the Server.

The failure is when I am using the external Server to run my gamePad code to find the sound file when all my source code is loaded onto my Server. In this case, the sound does not play.

FILE HIERARCHY

games folder
   Game_1 folder
      game1.html
      Game_Support folder
         audio folder
         js folder

HTML

<body onload="doBodyOnLoad()">

JS:

function doBodyOnLoad() {

    $(document).ready(function() {

        // ... //

    });   // $(document).ready

}   // doBodyOnload


function setupKeypresses() {

    $(document).keydown(function(evt) {
        
        let code = evt.keyCode || evt.which;

        // for example:
        if (code === "R")
        {
            movePaddleRight();  // this will call ouch() below
        }
            
    });
    
}   // setupKeypresses


function PlaySound(id, src) {

    let theSound = new Audio();
    theSound.src = src;
    
    theSound.play();
    
}   // PlaySound


function ouch() {

    updateScore(--thisScore);
    
    // even the absolute path doesn't work ?
//  var theSnd = "http://lovesongforever.com/games/Game_1/Game_1_Support/audio/explosion.mp3";
    var theSnd = "Game_1_Support/audio/explosion.mp3";
    PlaySound("audioPlaceHolder", theSnd);
            
    // fade either the whole Board (okay), or just the Paddle (not! so much)
    doFade("#gameBoard");   // doFade("#gameBoard > #gamePaddle") [not ready for Prime Time]

}   // ouch

Thanks bunches for your patience with me!

1

There are 1 answers

4
nondebug On

This is because you're trying to autoplay an Audio element without user interaction to initiate the audio.

Firefox expresses a blocked play() call to JavaScript by rejecting the promise returned by HTMLMediaElement.play() with a NotAllowedError. All major browsers which block autoplay express a blocked play via this mechanism. In general, the advice for web authors when calling HTMLMediaElement.play(), is to not assume that calls to play() will always succeed, and to always handle the promise returned by play() being rejected.

https://hacks.mozilla.org/2019/02/firefox-66-to-block-automatically-playing-audible-video-and-audio/

I think it will work if you click or tap on the page first. Gamepad button presses may work for this too depending on the implementation.