3

I'm playing system sounds using AudioServicesPlaySystemSoundWithCompletion and custom sounds using AVAudioPlayer.

Why are sounds played if the silent switch is on? I've tried all the categories for the "AVAudioSession".

I tried the following code:

 try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategorySoloAmbient)
 try AVAudioSession.sharedInstance().setActive(true)

Also tried this:

try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)

I tried all the categories defined in this link, but the sounds are always playing when the phone is muted (silent switch ON). https://developer.apple.com/reference/avfoundation/avaudiosession/audio_session_categories

I'm playing the sounds like this:

System sounds:

AudioServicesPlaySystemSoundWithCompletion(1304, nil)

Custom sounds:

        let url = Bundle.main.url(forResource: "sound01", withExtension: ".wav")
        do {
            if audioPlayer != nil {
                audioPlayer!.stop()
                audioPlayer = nil
            }
            if let soundURL = soundURL {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
                try AVAudioSession.sharedInstance().setActive(true)
                audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
            }
            guard let audioPlayer = audioPlayer else {
                return
            }
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch let error {
            print(error.localizedDescription)
        }

Am I doing something wrong?

user3427013
  • 1,039
  • 1
  • 13
  • 28

1 Answers1

3

The fix was to use the AudioServicesPlayAlertSound function instead of the AudioServicesPlaySystemSoundWithCompletion function.

We also can't use AVAudioPlayer. We need to use the AudioServicesPlayAlertSound function by creating a sound ID for each custom sound.

let soundURL = Bundle.main.url(forResource: "test01", withExtension: ".wav")

if let soundURL = soundURL {
      var soundID : SystemSoundID = 0
      AudioServicesCreateSystemSoundID(soundURL as CFURL, &soundID)
      AudioServicesPlayAlertSound(soundID)
}
user3427013
  • 1,039
  • 1
  • 13
  • 28
  • can you help on this: https://stackoverflow.com/questions/70875385/why-sound-still-play-when-devices-silent-mode-is-on/70875992#70875992 – Kishan Bhatiya Jan 27 '22 at 11:16