如何在iOS App中实现朗读发声功能

1. 包含头文件:

#import 

2. 声明变量:

@property(nonatomic,strong)AVSpeechSynthesizer*synthesizer;
@property(nonatomic,strong)AVSpeechUtterance*utterance;

3. 初始化点击按钮,初始化"语音合成器":

    //开始朗读按钮
    UIButton *selectedBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    selectedBtn.frame = CGRectMake(0, 0, 100, 35);
    [selectedBtn setTitle:@"开始朗读" forState:UIControlStateNormal];
    [selectedBtn addTarget:self action:@selector(clickedToReadBtn:) forControlEvents:UIControlEventTouchUpInside];
    [selectedBtn.titleLabel setTextAlignment:NSTextAlignmentCenter];
    selectedBtn.titleLabel.center = selectedBtn.center;
    UIBarButtonItem *selectItem = [[UIBarButtonItem alloc] initWithCustomView:selectedBtn];
    self.navigationItem.rightBarButtonItem =selectItem;
    
    //语音合成器
    _synthesizer=[[AVSpeechSynthesizer alloc] init];

4. 实现朗读功能:

- (void)clickedToReadBtn:(UIButton*)btn {
    NSLog(@"clickedToReadBtnclickedToReadBtn");
    
    NSString *oriString = _displayPinYinContStr;

    if ([oriString isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"请输入要朗读中文语句", nil)];
        return;
    }
//    NSString *oriString=@"你好!通过嘴巴用舌头说话通过嘴巴用舌头说话通过嘴巴用舌头说话通过嘴巴用舌头说话";
    //舌头
    _utterance=[[AVSpeechUtterance alloc] initWithString:oriString];
    //如果识别中文,需设置voice参数
    NSArray*voices=@[[AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"],[AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"],[AVSpeechSynthesisVoice voiceWithLanguage:@"ja-JP"]];
    _utterance.voice=voices[0];
    //语速
    _utterance.rate=0.5;
    //音量
    _utterance.volume=0.8;
    //音调
    _utterance.pitchMultiplier=1;
    
    //通过嘴巴用舌头说话
    [_synthesizer speakUtterance:_utterance];
}

其它:

  1. iOS 语音播放文字内容--制作简易听书软件(AVSpeechSynthesizer)
  2. AVSpeechSynthesis使用详解

你可能感兴趣的:(如何在iOS App中实现朗读发声功能)