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

How to programmatically play audio even when iOS device is muted
Translate »