文本转语音

语音合成技术是iOS7推出的,可以实现无网络语音功能,支持多种语音。
1,导入AVFoundation.framework框架,在对应的文件中导入头文件#import
2,定义一个成员变量用来记录AVSpeechSynthesizer语音合成器
3,定义语音对象AVSpeechSynthesisVoice指定说话的语言
4,实例化发声对象 AVSpeechUtterance,指定要朗读的内容
5,指定语音,和朗诵速度 
6,启动语音

Demo


@interface KJSpeechSynthesizer : NSObject

+ (instancetype)sharedSpeechSynthesizer;

- (void)speakString:(NSString *)string;

- (void)stopSpeak;

@end

#import "KJSpeechSynthesizer.h"

@interface KJSpeechSynthesizer () 

@property (nonatomic, strong, readwrite) AVSpeechSynthesizer *speechSynthesizer;

@end

@implementation KJSpeechSynthesizer

+ (instancetype)sharedSpeechSynthesizer
{
    static id sharedInstance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[KJSpeechSynthesizer alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init
{
    if (self = [super init])
    {
        [self buildSpeechSynthesizer];
    }
    return self;
}

- (void)buildSpeechSynthesizer
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0)
    {
        return;
    }
    
    self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
    [self.speechSynthesizer setDelegate:self];
}
   // zh_CN 中文
   // en-US 英文
- (void)speakString:(NSString *)string
{
    if (self.speechSynthesizer)
    {
        AVSpeechUtterance *aUtterance = [AVSpeechUtterance speechUtteranceWithString:string];
        AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
        //设置语速 
       aUtterance.rate = 0.1
        [aUtterance setVoice:voice];
        
        if ([self.speechSynthesizer isSpeaking])
        {
            [self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryWord];
        }
        
        [self.speechSynthesizer speakUtterance:aUtterance];
    }
}

- (void)stopSpeak
{
    if (self.speechSynthesizer)
    {
        [self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
    }
}

你可能感兴趣的:(文本转语音)