iOS TTS封装

1.RLKTTS.h

//
//  RLKTTS.h
//  TTS
//
//  Created by Realank on 2017/8/2.
//  Copyright © 2017年 Realank. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface RLKTTS : NSObject

+ (void)stop;
+ (void)speekChinese:(NSString*)chinese complete:(void(^)())completeBlock;

@end

2.RLKTTS.m

//
//  RLKTTS.m
//  TTS
//
//  Created by Realank on 2017/8/2.
//  Copyright © 2017年 Realank. All rights reserved.
//

#import "RLKTTS.h"
#import <AVFoundation/AVFoundation.h>
@interface RLKTTS ()<AVSpeechSynthesizerDelegate>

@property (nonatomic, copy) void(^completeBlock)();
@property (nonatomic, strong) AVSpeechSynthesizer *synth;

@end
@implementation RLKTTS

+(instancetype) sharedInstance {
    static dispatch_once_t pred;
    static id shared = nil; //设置成id类型的目的,是为了继承
    dispatch_once(&pred, ^{
        shared = [[super alloc] init];
    });
    return shared;
}

+ (void)speekChinese:(NSString*)chinese complete:(void(^)())completeBlock{
    [[self sharedInstance] speekChinese:chinese complete:completeBlock];
}

+ (void)stop{
    [[self sharedInstance] stop];
}

- (void)stop{
    [_synth stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
    _synth = nil;
}

- (void)speekChinese:(NSString*)chinese complete:(void(^)())completeBlock{
    if (chinese.length == 0) {
        if (completeBlock) {
            completeBlock();
        }
        return;
    }
    _completeBlock = completeBlock;
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:chinese];
    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
    utterance.voice = voice;
    utterance.rate = AVSpeechUtteranceDefaultSpeechRate - 0.07;
    utterance.volume = 0.7;
    utterance.pitchMultiplier = 0.6;
    utterance.postUtteranceDelay = 1.2;
    NSLog(@"%@",[AVSpeechSynthesisVoice speechVoices]);
    _synth = [[AVSpeechSynthesizer alloc]init];
    _synth.delegate = self;
    [_synth speakUtterance:utterance];
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
    if (_completeBlock) {
        _completeBlock();
        _completeBlock = nil;
    }
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance *)utterance{
    if (_completeBlock) {
        _completeBlock();
        _completeBlock = nil;
    }
}


@end

用法:

[RLKTTS speekChinese:@"你好,吃了吗" complete:^{
        NSLog(@"complete");
    }];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 《裕语言》速成开发手册3.0 官方用户交流:iApp开发交流(1) 239547050iApp开发交流(2) 10...
    叶染柒丶阅读 28,405评论 5 19
  • 天天失眠到三四点,看来要买点儿酒备着了。 把这两天的画发一下,就睡吧,虽然肯定又睡不着。 在考虑要不要养一只猫?可...
    梧婷阅读 1,436评论 0 0
  • 巴山渝水--初见重庆 第一次对这个城市有印象来源于电影《从你的全世界路过》...李子坝穿过房屋的轻轨,时而上坡时而...
    e5497b4727d1阅读 4,007评论 4 3
  • 我的眼里有你,不胜欢喜。 你的眼里有我,此生荣幸。
    我要小马甲阅读 1,677评论 0 0