iOS7.0之后新添加了一些新的功能,里面就有系統(tǒng)自帶的語音播報(bào)庫, 需要 導(dǎo)入系統(tǒng)的AVFoundation 庫
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<AVSpeechSynthesizerDelegate>
/** 播報(bào)的內(nèi)容 */
@property (nonatomic, readwrite , strong) AVSpeechSynthesizer *synth;
/** 負(fù)責(zé)播放 */
@property (nonatomic, readwrite , strong) AVSpeechUtterance *utterance;
@end
基本使用
NSString *str = @"支付寶 到賬 100萬 元";
self.utterance = [AVSpeechUtterance speechUtteranceWithString:str];//成功集成語音播報(bào)
//pitchMultiplier: 音高
//
//postUtteranceDelay: 讀完一段后的停頓時間
//
//preUtteranceDelay: 讀一段話之前的停頓
//rate: 讀地速度, 系統(tǒng)提供了三個速度: AVSpeechUtteranceMinimumSpeechRate, AVSpeechUtteranceMaximumSpeechRate, AVSpeechUtteranceDefaultSpeechRate
self.utterance.rate = AVSpeechUtteranceDefaultSpeechRate;// 播報(bào)的語速
// 中式發(fā)音
AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
//英式發(fā)音
// AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-GB"];
self.utterance.voice = voice;
self.synth = [[AVSpeechSynthesizer alloc] init];
self.synth.delegate = self;// 設(shè)置代理
[self.synth speakUtterance:self.utterance];
代理方法
//已經(jīng)開始
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14)) {
}
//已經(jīng)說完
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14)) {
}
//已經(jīng)暫停
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14)) {
}
//已經(jīng)繼續(xù)說話
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didContinueSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14)) {
}
//已經(jīng)取消說話
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14)) {
}
//將要說某段話
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14)) {
}