How to programmatically use iOS voice synthesizers? (text to speech)

杀马特。学长 韩版系。学妹 提交于 2019-11-27 11:27:17
Onato

Starting from iOS 7, Apple provides this API.

See this answer.

Objective-C

#import <AVFoundation/AVFoundation.h>
…
AVSpeechUtterance *utterance = [AVSpeechUtterance 
                            speechUtteranceWithString:@"Hello World!"];
AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
[synth speakUtterance:utterance];

Swift

import AVFoundation
…
let utterance = AVSpeechUtterance(string: "Hello World!")
let synth = AVSpeechSynthesizer()
synth.speakUtterance(utterance)
user2518512
#import <AVFoundation/AVFoundation.h>

AVSpeechSynthesizer *av = [[AVSpeechSynthesizer alloc] init];
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:@"Text to say"]; 
[av speakUtterance:utterance];

This code worked for me with Swift and iOS 8 on both Simulator and iPhone 6. I needed to add the standard AVFoundation library:

import AVFoundation

// ...

func onSayMeSomething() {
    let utterance = AVSpeechUtterance(string: "Wow! I can speak!")
    utterance.pitchMultiplier = 1.3
    utterance.rate = AVSpeechUtteranceMinimumSpeechRate * 1.5
    let synth = AVSpeechSynthesizer()
    synth.speakUtterance(utterance)
}
yuji

Unfortunately iOS doesn't expose a public API for programmatically generating speech.

There is a private API you can use, if you're not submitting to the App Store.

Otherwise, see the responses to this question for a number of third-party libraries you can use.

you could find this helpful Making Your iPhone Application Accessible

As stated in “iPhone Accessibility API and Tools,” standard UIKit controls and views are automatically accessible. If you use only standard UIKit controls, you probably don’t have to do much additional work to make sure your application is accessible. In this case, your next step is to ensure that the default attribute information supplied by these controls makes sense in your application. To learn how to do this, see “Supply Accurate and Helpful Attribute Information.”

You can try these third party APIs: iSpeech or OpenEars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!