iOS文本朗读

iOS中文本朗读需要使用AVFoundation框架

1.首先要了解两个类充当的角色

AVSpeechSynthesizer相当于一个DVD

AVSpeechUtterance相当于一个磁盘

2.AVSpeechSynthesizer的属性和方法

delegate 代理,用于监听朗读器的开始、暂停、停止和完成等等操作的

speaking 是否正在朗读

paused 是否暂停

  • (void)speakUtterance:(AVSpeechUtterance *)utterance;
    使用该方法向语音队列里添加需要朗读的语句,然后会按着添加顺序依次朗读
  • (BOOL)stopSpeakingAtBoundary:(AVSpeechBoundary)boundary;
    停止朗读
  • (BOOL)pauseSpeakingAtBoundary:(AVSpeechBoundary)boundary;
    暂停朗读
  • (BOOL)continueSpeaking;
    继续朗读

3.AVSpeechUtterance的属性和方法

  • (instancetype)speechUtteranceWithString:(NSString *)string;

  • (instancetype)initWithString:(NSString *)string;
    两个初始化方法,参数是你需要朗读的文字

voice AVSpeechSynthesisVoice,设置朗读文字的语言,如果不设置会默认为当前系统的语言,

    使用[NSLocale availableLocaleIdentifiers]可以获取语言列表

rate 0.0-1.0,设置朗读的速度

pitchMultiplier 0.5-2.0,设置朗读的音调

volume 0.0-1.0,朗读的声音大小

preUtteranceDelay 距离上一句结束的间隔

postUtteranceDelay 下一句朗读距离该句结束开始的间隔

下面是一个简单的朗读代码

    _speechSynthesizer = [[AVSpeechSynthesizer alloc] init];


    NSArray *array = @[@"Hello sun!",
                       @"开始说中文?",
                       @"其他的语言我不知道能不能行"];

    for(NSString *str in array){

        AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:str];
        utterance.rate = 0.5;
        utterance.pitchMultiplier = 0.8;
        utterance.volume = 0.5;
        utterance.postUtteranceDelay = 0.1;
        [_speechSynthesizer speakUtterance:utterance];
    }
发布了34 篇原创文章 · 获赞 4 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章