ARTICLES

How to programmatically play audio even when iOS device is muted

If you want to play the sound from a video or audio clip even when the iPhone or iPad device is muted you can use AVAudioSession to accomplish the task.  This will make your app work similar to YouTube.

You will want to set the AVAudioSession category to AVAudioSessionCategoryPlayback.  The session is a singleton so you only need to set it once, either shortly after app launch or prior to your audio or video playing.

Below is some sample Swift 3 code:

//Set the audio session to playback to ignore mute switch on device
do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    } catch {
        //Didn't work
}

Your code to play the audio or video will remain unchanged. Below is an example using AVPlayer and AVPlayerViewController() in Swift 3. Don’t forget to keep a reference to the AVPlayer while the video is playing.

self.player = AVPlayer(url: videoURL)
if self.player != nil {
    let playerViewController = AVPlayerViewController()
    playerViewController.player = self.player
    presentingViewController.present(playerViewController, animated: true) {
    playerViewController.player!.play()
    }
}

Apple Documentation:

AVAudioSession

AVAudioSessionCategoryPlayback

AVPlayer

AVPlayerViewController

 

Tested with:

Xcode 8.2.1

iOS 10.2.1



Our Products

Kitemetrics
Keyword level attribution for Apple Search Ads. Optimize your bids and increase your revenue. Sign up for free at kitemetrics.com.

White Noise and Deep Sleep Sounds
Calming and relaxing sounds that will help you sleep like a baby tonight.
Download for free from the App Store.
Get it on Google Play.




Our Sponsors

Get Sleepy
Get Sleepy
The free podcast that puts you to sleep with meditative bedtime stories. Listen at getsleepy.com.