Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Audio when device in silent mode - ios swift

Tags:

ios

swift

audio

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. How can I do it?

I am using the following code to play audio

currentAudio!.stop()
currentAudio = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sample_audio", ofType: "mp3")!));
            
currentAudio!.currentTime = 0
currentAudio!.play();
like image 536
Amsheer Avatar asked Feb 09 '16 10:02

Amsheer


2 Answers

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)
}
like image 108
rushisangani Avatar answered Oct 13 '22 19:10

rushisangani


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")
    }
}
like image 27
maxwell Avatar answered Oct 13 '22 19:10

maxwell