What and why
AVSpeechSynthesis basics
synthesizer 생성
let synthesizer = AVSpeechSynthesizer()
utterance를 만들고, 이를 synthesizer에 dispatch한다.
let utterance = AVSpeechUtterance(string: "Hello")
synthesizer.speak(utterance)
내부적으로 AVAudioSession이 자동으로 활성화된다.
다른 audio와 섞기 위해서는 다음과 같이 한다.
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,
with: .mixOthers)
다른 오디오 볼륨을 일시적으로 줄이기 위해서는 다음과 같이.
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,
with: .duckOthers)
이 때 shared audio session을 쓰기 때문에, 다른 오디오가 끊기는 것을 막지않기 위해 inactive는 하지 않는다. → 하고 싶으면 스스로 한다.
Delegate를 통해서 음성 중간중간을 후킹할 수 있다.
synthesizer.delegate = self
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance)
{
print("Speech started")
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
print("Speech finished")
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
guard let rangeInString = Range(characterRange, in: utterance.speechString()) else { return }
print("Will speak: \\(utterance.speechString[rangeInString])")
}
Choosing the right voice
let utterance = AVSpeechUtterance(string: "Hello")
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
let allVoices = AVSpeechSynthesisVoice.speechVoices()
utterance.voide = AVSpeechSynthesisVoice(identifier: allVoices[0].identifier)
Rate, Pitch, and volume
let utterance = AVSpeechUtterance(string: "Hello")
utterance.rate = 0.75
utterance.rate = 0.25
utterance.rate = AVSpeechUtteranceDefaultSpeechRate
utterance.rate = AVSpeechUtteranceMaximumSpeechRate
Attributed strings
Attribute를 통해서 speech를 커스텀할 수 있다.
IPA(International Phonetic Alphabet) Notation 사용
let attributedString = NSMutableAttributedString(string: "Hello iPhone")
attributedString.addAttribute(.accessibilitySpeechIPANotation, value: "(발음기호)", range: NSRange(location: 6, length: 6)))