I am creating an application using xcode 7.1, swift. I want to play an audio. Everything is fine. Now my problem I want to hear sound when the device in silent mode or muted
Swift 4.2
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
} catch let error {
print("Error in AVAudio Session\(error.localizedDescription)")
}
import AVKit
And add this to your AppDelegate's applicationDidBecomeActive
section
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch {
print(error.localizedDescription)
}
} catch {
print(error.localizedDescription)
}
}
Swift 5.0.1
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
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: [])
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)
}