Help needed playing multiple sounds

I would like to be able to player several sounds from script and have sliders animate for a breath timing app.

It appears that the browser only allows 1 sound to be played on one user interaction --clicking a button.

I tried using javascript in the standard page html to play sounds and while it works on a windows laptop, only the first sound works on an iphone.

<audio id="audio1" src="_/theme/beep1.mp3" autostart="false" ></audio>
<audio id="audio2" src="_/theme/beep2.mp3" autostart="false" ></audio>

<script>
    function PlaySound1() {
        var sound1 = document.getElementById("audio1");
        sound1.play()
        }

    function PlaySound2() {
        var sound2 = document.getElementById("audio2");
        sound2.play()
        } 
    
    function PlayAudio1() {
        var audio1 = new Audio('_/theme/beep1.mp3');
        audio1.play();
        }

    function PlayAudio2() {
        var audio1 = new Audio('_/theme/beep2.mp3');
        audio1.play();
        }
    
</script>

I tried using speech synthesize but it is too slow on the windows laptop, but fast enough on the iphone to synthesize speech for counting down numbers along with animating a slider.

from anvil.js.window import speechSynthesis as synth

def breathe_in(self):
      synth.speak(anvil.js.window.SpeechSynthesisUtterance("in"))
      time.sleep(0.1)

I’d prefer to have custom sounds that can be used to make each sound required after one button click, such that it guides a person with their breathing over multiple breathing cycles.
e.g. “in”, “3”, “2”, “1”, “hold”, “out” etc.

My app is available for viewing at Anvil | Login

I suspect that may be a hard constraint on Apple devices (but not an expert, so take with a grain of salt).

Can you append the two mp3s together so it’s just one file you’re playing?

Ok, I have now had some success adapting the solution here to work around this iOS limitation:

Let me know if you’d like more details about how I implemented it.

Yes please, that would be great.

1 Like

Ok, here you go. I haven’t directly tested this on Safari, but it is a simpler version of code that has been tested on Safari and found to work.

https://anvil.works/build#clone:BCMO2OF5NBHEQS47=2L4RYZJA22VTZCOQF3ELVJHF

It’s a variation on the stackoverflow prescription. Instead of playing a short, silent sound to initialize the audio element (which might be better, depending), I just turn the volume to 0 and play it that way in response to a user click.

My Anvil code was initially adapted from this (and related posts), but that older sample app may no longer work due to the hardcoded audio url being broken.

1 Like