文本转语音

语音合成技术是iOS7推出的,可以实现无网络语音功能,支持多种语音。
1,导入AVFoundation.framework框架,在对应的文件中导入头文件#import <AVFoundation/AVSpeechSynthesis.h>
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 () <AVSpeechSynthesizerDelegate>

@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];
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • iOS文本转语音技术 文本转语音技术, 也叫TTS, 是Text To Speech的缩写. iOS如果想做有声书...
    windgo阅读 4,592评论 7 10
  • 在iOS中我们想把文本转换成语音使用的AVFoundation框架中的AVSpeechSynthesizer。比如...
    燃烧的大叔阅读 1,174评论 0 1
  • 文本转语音,一般会用在无障碍开发。下面介绍如何使用Python实现将文本文件转换成语音输出。 [toc] 准备 我...
    尽情的嘲笑我吧阅读 1,950评论 0 7
  • 我的blog原文地址https://xing-ou.github.io/2016/05/12/ios文本到语音/今...
    xingou阅读 2,806评论 1 1
  • 方向是太阳升起的地方 舵手只有自己 每个人都在掌舵 当双眼眩晕 沉沉地坠入海里 清清楚楚的看见你 即便一触既破 就...
    大榕树上阅读 194评论 1 1

友情链接更多精彩内容