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
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")
}
}
You can go through this, it will help you out
When you use following audio session categories, sounds will not be muted on iOS: AVAudioSessionCategoryPlayback,AVAudioSessionCategoryRecord,AVAudioSessionCategoryPlayAndRecord
Example
func playSound (Sound: String, Type: String) {
//Prepare the sound file name & extension
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(Sound, ofType: Type)!)
//Preparation to play
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
//Play audio
var error: NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}