iosswiftavspeechsynthesizeravspeechutterance

Force custom pronunciation of words in AVSpeech and AVSpeechUtterance in Swift


For speaking out numbers with an AVSpeechUtterance, I would like Siri to speak numbers in ways that respect the convention for the type of number.

For a date, I would like it to pronounce 1492 as fourteen ninety two rather then one thousand, four hundred, ninety-two.

For the phone number 650-412-3456, I would like it to say six five oh, four one two three four five six as opposed to six hundred fifty dash four hundred 12 dash three,thousand four hundred fifty six.

Is there anyway to specify pronunciation using AVSpeech and AVUtterance? There does not seem to be anything obvious in the docs.


Solution

  • While not an AV setting, parsing the phrase for the speaker would get the desired results.

    For example, using the extension below:

    let number = "1492"
    let phrase = number.separate(every: 2, with: " ")
    print(phrase) // 14 92
    

    And for the phone:

    let phone   = "650-412-3456"
    let parts = phone.components(separatedBy: CharacterSet.decimalDigits.inverted)
    var phrase2 = String()
    
    for part in parts {
      if Int(part) != nil {
        phrase2.append(String(describing: part).separate(every: 1, with: " ") + ",")
      }
    } 
    
    print(phrase2) // 6 5 0,4 1 2,3 4 5 6,
    

    Commas were added for a more natural reading by the speech synthesizer but they could be left off.

    String extension from Joe Maher:

    extension String {
      func separate(every: Int, with separator: String) -> String {
        return String(stride(from: 0, to: Array(self).count, by: every).map {
           Array(Array(self)[$0..<min($0 + every, Array(self).count)])
           }.joined(separator: separator))
      }
    }