1.導(dǎo)入框架 AVFoundation
注意:三個(gè)關(guān)鍵類
AVSpeechSynthesizer: 可以假想成一個(gè)可以說話的人
AVSpeechSynthesisVoice: 可以假想成人的聲音
AVSpeechUtterance: 可以假想成要說的一段話
#import <Foundation/Foundation.h>
@interface TmfSpeakTool : NSObject
- (void)transtoVoiceWithString:(NSString *)str;
- (void)pauseAv;
@end
#import <AVFoundation/AVFoundation.h>
@interface TmfSpeakTool ()<AVSpeechSynthesizerDelegate>
@property (nonatomic, strong) AVSpeechSynthesizer *aVSpeechSynthesizer;
//@property(nonatomic)float pitchMultiplier;// [0.5 - 2] Default = 1园爷,聲調(diào)泰讽,不怕逗死你就設(shè)成2
@end
@implementation TmfSpeakTool
- (AVSpeechSynthesizer *)aVSpeechSynthesizer{
if (!_aVSpeechSynthesizer) {
_aVSpeechSynthesizer = [[AVSpeechSynthesizer alloc] init];
_aVSpeechSynthesizer.delegate = self;
}
return _aVSpeechSynthesizer;
}
- (void)pauseAv{
if (self.aVSpeechSynthesizer.paused) {
[self.aVSpeechSynthesizer continueSpeaking];
}else{
[self.aVSpeechSynthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
}
- (void)transtoVoiceWithString:(NSString *)str{
if (self.aVSpeechSynthesizer.speaking)
return;
AVSpeechUtterance * aVSpeechUtterance = [[AVSpeechUtterance alloc] initWithString:str];
aVSpeechUtterance.rate = AVSpeechUtteranceDefaultSpeechRate;// 設(shè)置語速庭惜,范圍0-1疚颊,注意0最慢羡榴,1最快兴溜;
aVSpeechUtterance.voice =[AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//設(shè)置發(fā)音却妨,這是中文普通話
[self.aVSpeechSynthesizer speakUtterance:aVSpeechUtterance];//開始閱讀
}
#pragma mark - =========AVSpeechSynthesizerDelegate =========
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance{
NSLog(@"開始閱讀");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
[self.aVSpeechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
NSLog(@"閱讀完畢");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance *)utterance{
NSLog(@"閱讀暫停");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didContinueSpeechUtterance:(AVSpeechUtterance *)utterance{
NSLog(@"閱讀繼續(xù)");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance *)utterance{
}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance{
}