Play Audio when device in silent mode - ios swift

Put this line before calling play() method of AVPlayer.

In Objective C

[[AVAudioSession sharedInstance]
            setCategory: AVAudioSessionCategoryPlayback
                  error: nil];

In Swift

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch {
    // report for an error
}

Swift 5

do {
    try AVAudioSession.sharedInstance().setCategory(.playback)
} catch(let error) {
    print(error.localizedDescription)
}

Swift 4

use this line before play video

try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])

You can use AppDelegate class.

For enable sound (for audio or video) when device is in silent mode use AVAudioSessionCategoryPlayback:

func applicationDidBecomeActive(_ application: UIApplication) {

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    } catch {
        print("AVAudioSessionCategoryPlayback not work")
    }
}

For disable sound when device is in silent mode (for example when we answer the phone call) use AVAudioSessionCategorySoloAmbient:

func applicationWillResignActive(_ application: UIApplication) {

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategorySoloAmbient)
    } catch {
        print("AVAudioSessionCategorySoloAmbient not work")
    }
}

Swift 3.0 and Xcode > 8

Play sound in Video when device is on RINGER mode and SLIENT mode

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        //print("AVAudioSession Category Playback OK")
        do {
            try AVAudioSession.sharedInstance().setActive(true)
            //print("AVAudioSession is Active")
        } catch _ as NSError {
            //print(error.localizedDescription)
        }
    } catch _ as NSError {
        //print(error.localizedDescription)
    }

Tags:

Ios

Audio

Swift