Skip to content

Instantly share code, notes, and snippets.

@SteveTrewick
Last active February 20, 2017 11:06
Show Gist options
  • Save SteveTrewick/8022008a4fff24dd3fdc to your computer and use it in GitHub Desktop.
Save SteveTrewick/8022008a4fff24dd3fdc to your computer and use it in GitHub Desktop.
Set AVAudioSession category and options to mix with other audio and turn volume down/up as well as interrupt any spoken text.
import UIKit
import AVFoundation
class ViewController: UIViewController, AVSpeechSynthesizerDelegate {
let synth = AVSpeechSynthesizer()
let avsesh = AVAudioSession.sharedInstance()
let voice = AVSpeechSynthesisVoice(language: "en-GB")
let avopts:AVAudioSessionCategoryOptions = [
.MixWithOthers,
.DuckOthers,
.InterruptSpokenAudioAndMixWithOthers
]
let avcat = AVAudioSessionCategoryPlayback
override func viewDidLoad() {
super.viewDidLoad()
do {
try avsesh.setCategory(avcat, withOptions: avopts)
}
catch let error as NSError {
print("error setting audio category: \(error)")
}
self.synth.delegate = self
}
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didFinishSpeechUtterance utterance: AVSpeechUtterance) {
do { try avsesh.setActive(false) }
catch{/*meh*/}
}
func speak(words:String) {
let words = AVSpeechUtterance(string: words)
words.voice = self.voice // or pass this in, whatever
synth.speakUtterance(words)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment