Reputation: 383
I can't get the iOS 7 AVSpeechSynthesizer
to work when my iOS app is in background mode. I have added the "App plays audio" key to the app's supported background modes, but I still can't get it to work.
I have also investigated the possibility of creating an AVMutableCompositionTrack
, with an AVSpeechSynthesizer
utterance, and then somehow play it with a player that would be able to run in the background - but with no luck.
Did anyone have better luck than me in using AVSpeechSynthesizer
in the background?
Upvotes: 27
Views: 9879
Reputation: 3096
@imihaly has told "You must set "Audio and AirPlay" in background modes."
that is understandable
You need to enable that from there, Second, in the AVSpeechSynthesizer code section you have to write below code
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setCategory(
AVAudioSession.Category.playback,
options: AVAudioSession.CategoryOptions.duckOthers
)
Upvotes: 0
Reputation: 149
This code works for me in Swift 5
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: AVAudioSession.CategoryOptions.mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print(error)
}
let utterance = AVSpeechUtterance(string: voiceOutdata)
let synth = AVSpeechSynthesizer()
synth.speak(utterance)
According to https://forums.developer.apple.com/thread/38917
AVAudioSessionCategoryOptionMixWithOthers is added along with the Playback Category when the session is mixable there are some internal checks as to the "why" an application is awake before it is allowed to play audio.
Upvotes: 9
Reputation: 953
For swift 3, import AVKit (or AVFoundation) then add
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
to viewWillAppear(). This allows audio to play regardless of the mute switch status and in the background with the screen off.
*Edit: AVAudioSession is defined in AVFoundation and is also available with AVKit
*Edit 2: Screenshot of auto complete showing that AVAudioSession is available in AVKit
Upvotes: 9
Reputation: 1858
NSError *error = NULL;
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
if(error) {
// Do some error handling
}
[session setActive:YES error:&error];
if (error) {
// Do some error handling
}
Upvotes: 43