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

1. 包含头文件:

#import <AVFoundation/AVFoundation.h>

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使用详解
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容