Last active
February 20, 2017 11:06
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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