Enabling Spoken Audio Sessions - Multimedia - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 12. Multimedia

12.3 Enabling Spoken Audio Sessions

Problem

You have an eBook reading app (or similar app) and would like to enable a specific audio session that allows your app’s audio to be paused--but another app is playing back voice on top of yours (such as an app that provides navigation information with voice).

Solution

Follow these steps:

1. Go through the available audio session categories inside the availableCategories property of your audio session and find AVAudioSessionCategoryPlayback.

2. Go through values inside the availableModes property of your audio session (of type AVAudioSession). If you cannot find AVAudioSessionModeSpokenAudio, exit gracefully.

3. After you find the AVAudioSessionModeSpokenAudio mode, set your audio category to AVAudioSessionCategoryPlayback using the setCategory(_:withOptions:) method of the audio session.

4. Activate your session with the setActive(_:withOptions:) method of your audio sessio.

Discussion

Suppose you are developing an eBook app and have a “Read” button in the UI that the user presses to ask the app to read the contents of the book out loud. For this you can use the AVAudioSessionModeSpokenAudio audio session mode, but you have to check first whether that mode exists or not. Use the availableModes property of your audio session to find this information out.

Let’s work on an example. Let’s find the AVAudioSessionCategoryPlayback category and the AVAudioSessionModeSpokenAudio mode:

let session = AVAudioSession.sharedInstance()

guard session.availableCategories.filter(

{$0 == AVAudioSessionCategoryPlayback}).count == 1 &&

session.availableModes.filter(

{$0 == AVAudioSessionModeSpokenAudio}).count == 1 else{

print("Could not find the category or the mode")

return

}

After you confirm that our category and mode are available, set the category and mode and then activate your audio session:

do{

try session.setCategory(AVAudioSessionCategoryPlayback,

withOptions:

AVAudioSessionCategoryOptions.InterruptSpokenAudioAndMixWithOthers)

try session.setMode(AVAudioSessionModeSpokenAudio)

try session.setActive(true, withOptions:

AVAudioSessionSetActiveOptions.NotifyOthersOnDeactivation)

} catch let err{

print("Error = \(err)")

}

See Also