Skip to content

Instantly share code, notes, and snippets.

@ryanlintott
Last active October 12, 2022 13:47
Show Gist options
  • Save ryanlintott/e1284682216d4e4a90fa474a676fb453 to your computer and use it in GitHub Desktop.
Save ryanlintott/e1284682216d4e4a90fa474a676fb453 to your computer and use it in GitHub Desktop.
Extension to AVSpeechSynthesizer that will speak IPA (International Phonetic Alphabet) strings
import Foundation
import AVFoundation
@available(iOS 10.0, *)
extension AVSpeechSynthesizer {
func speakIPA(_ ipaString: String, voiceIdentifier: String, willSpeak: ((String) -> Void)? = nil) {
//Set the audio session to playback to ignore mute switch on device
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, options: [.interruptSpokenAudioAndMixWithOthers, .duckOthers])
} catch {
print("Error: \(error.localizedDescription)")
}
let mutableAttributedString = NSMutableAttributedString(string: ipaString)
let range = NSString(string: ipaString).range(of: ipaString)
let pronunciationKey = NSAttributedString.Key(rawValue: AVSpeechSynthesisIPANotationAttribute)
mutableAttributedString.setAttributes([pronunciationKey: ipaString], range: range)
let utterance = AVSpeechUtterance(attributedString: mutableAttributedString)
let voice = AVSpeechSynthesisVoice(identifier: voiceIdentifier)
utterance.voice = voice
// Pausing first is safer and may prevent bugs
self.pauseSpeaking(at: .immediate)
self.stopSpeaking(at: .immediate)
// Run some code just before speaking
willSpeak?(utterance.speechString)
print("speakIPA: \(ipaString) voice: \(voice?.identifier ?? "?")")
self.speak(utterance)
}
}
@jhoughjr
Copy link

jhoughjr commented Oct 12, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment