Playing sounds in mobile browsers

Hi All,

I’ve searched several related threads, but I still can’t find a working workaround for playing sounds in a mobile Safari browser. I understand that modern browsers’ security prevents a website from playing audio - unless the user explicitly permits this. I cannot work out how to do this in Xojo web (2019 r2). My guess is that I need to add button to the webpage by Javascript (not by Xojo IDE), and then invoke a script that opens the audio source when the js button is pressed.

So far, I have built a card game app which executes js, stored as a constant, to play a sound effect. This currently works fine on all Windows browsers, and on all Android browsers (tested up to Android 8.1) - but does not work on any Safari mobile browsers. For these browsers I am happy to add an “Enable Sounds” button - but I have no idea how to implement.

Very grateful if anyone can help!

Many thanks Michel. This looks useful - if I can get my head around how to integrate these js techniques into a Xojo webapp. :+1:

This may help:

You can also simply search for “run javascript” in the Web channel.

I have finally got it working! (tested on Windows(Edge / Chrome / Firefox) - Android 8.1 (native browser & Chrome) - IOS 12.5.2 iPad (Safari).

This seems really simple to implement - Place the following code (change the audio file sources to suit your own setup) into the App HTLMHeader property.
FYI, the below code was adapted from here.

//<div id="lockeddiv" > </div>
var sound1 = new Audio("https://yourserverURL/soundeffect1.mp3")
var sound2 = new Audio("https://yourserverURL/soundeffect2.mp3")
var nothing = new Audio("https://yourserverURL/nothing.wav")

var allAudio = []


var tapped = function() {
// Play all audio files on the first tap and stop them immediately.
	if(allAudio) {
		for(var audio of allAudio) {
			audio.currentTime = 0
      allAudio = null 
document.body.addEventListener('touchstart', tapped, false)
document.body.addEventListener('click', tapped, false)  
//Check if audio starts already unlocked by playing a blank wav. {

You might notice there are some commented code lines (ie the first line with the Div definition) that seem irrelevant - but, for me, the audio fails to play on ios safari if I delete the line. I have no idea why!

Once you have the above code in App.HTMLHeader, you can then play any of the audio files from any XOJO method (in the webpage) with a command like this:-


Many thanks to Michel_Bujardet for sending me in the right direction, and thanks to for the code snippets.

Forum for Xojo Programming Language and IDE. Copyright © 2021 Xojo, Inc.