Learn Courses My Dashboard

How to play sound when phone is in silent mode

Hello community! I want to play an alert sound, which has to work when the user’s device is on silent. Right now it does not play in this situation, only when the phones ringtone is activated. I found an article regarding this but could not make sense of it: Play Audio when device in silent mode - ios swift - Stack Overflow

Thx in advance for any help and thank you in general. I have been working on my first app for half a year now and would not have made it nearly this far without your support or the codewithchris videos.

This is how I play the sound, it may be a bit unconventional but it works well:

func playSound() {
    var filePath: String?
    filePath = Bundle.main.path(forResource: "warHorn", ofType: "wav")     // For you should be siren  and mp3
    let fileURL = URL(fileURLWithPath: filePath!)
    var soundID:SystemSoundID = 0

    AudioServicesCreateSystemSoundID(fileURL as CFURL, &soundID)
    AudioServicesPlaySystemSound(soundID)

// let sound = Bundle.main.path(forResource: “warHorn”, ofType: “wav”)
// self.audioplayer = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!))
// self.audioplayer.play()
}

solution found here: Play A Sound Using AVAudioPlayer [Swift 5 Example]
Additionally the AV Player had to be declared as a State variable, for the Code on the website to work in SwiftUI, like so:

@State var player: AVAudioPlayer?