美文网首页
如何在iOS App中实现朗读发声功能

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

作者: 不要虚度美好的时光 | 来源:发表于2022-02-02 17:29 被阅读0次

    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使用详解

    相关文章

      网友评论

          本文标题:如何在iOS App中实现朗读发声功能

          本文链接:https://www.haomeiwen.com/subject/tijrkrtx.html