Studio Niantic: Sound not working on IOS mobile browsers

I’m having an issue where the background music in the game doesn’t seem to work properly on mobile iOS browsers, while it works fine on Android devices.

Below is a snippet of my code in the project.
GameManeger.ts script

ecs.defineState('InitialGame').initial()
  .onEvent('EventPlayGame', 'PreGame', {target: world.events.globalId})
  .onEnter(() => {
    handleContinueGame()
  })
ecs.defineState('PreGame')
  .onEvent('RemoveCountDown', 'InGame', {target: world.events.globalId})
  .onEnter(() => {
    const curSche = schemaAttribute.cursor(eid)
    ChangeAnimationCharacter(world, curSche, 'idle')
    dataAttribute.cursor(eid).isLand = true
    curSche.currentModel = curSche.modelIdleChar
    curSche.isDie = false
  })
ecs.defineState('InGame')
  .onEvent('GameOverEvent', 'AfterGame', {target: world.events.globalId})
  .onEnter(() => {
    PlaySound(0)
  })
ecs.defineState('AfterGame')
  .onEvent('ReplayEvent', 'InitialGame', {target: world.events.globalId})
  .onEnter(() => {
    const curSche = schemaAttribute.cursor(eid)
    StopSound(0)
    PlaySound(4)
  })

SoundManger.js

const audioUrls = [‘https://firebasestorage/Surfing_BGM.mp3?alt=media’,
https://firebasestorage/Surfing_Jump.mp3?alt=media’,
https://firebasestorage/Surfing_Impact_short.mp3?alt=media’,
https://firebasestorage/Surfing_Bonus.mp3?alt=media’,
https://firebasestorage/Surfing_Finish.mp3?alt=media’,
]

const soundBG = new Audio(audioUrls[0])
const jumpSfx = new Audio(audioUrls[1])
const impactSfx = new Audio(audioUrls[2])
const bonusSfx = new Audio(audioUrls[3])
const finishSfx = new Audio(audioUrls[4])
const sounds = [soundBG, jumpSfx, impactSfx, bonusSfx, finishSfx]

function PlaySound(type) {
if (type === 0) {
sounds[type].loop = true
}
sounds[type].currentTime = 0
sounds[type].play()
}

function StopSound(type) {
sounds[type].pause()
}
export {PlaySound, StopSound}

I’ve researched this issue online, and it seems that Apple has its own policies to protect user experience by restricting autoplay of content with sound. Is that correct?
Is there any way to solve the problem of autoplaying sound on IOS browser?

The easiest way to solve this is by creating a prompt before your game starts such as a “Start Game” button that serves as the method to catch user input and allow the AudioContext to start.

1 Like

Hi @GeorgeButler
What about the sounds when objects in the game collide with each other. I still haven’t been able to solve that problem.

Try adding something like this to your custom component.

world.events.addListener(component.eid, ecs.physics.COLLISION_START_EVENT, (e) => {
  ecs.Audio.set(world, component.eid, {
    url: 'assets/bump.mp3',
    paused: false,
    positional: true,
    refDistance: 3, // You might need to play with this value depending on the scale of your scene.
  })
})