美文网首页
iOS 文本转语音

iOS 文本转语音

作者: sergeant | 来源:发表于2019-07-22 20:58 被阅读0次

    AV Foundation框架提供了将文本转换为语音的方法。

    主要涉及到三个类:

    • AVSpeechSynthesisVoice。语音类,目前有37种语音,但是不支持自定义语音。
    • AVSpeechUtterance。最小的播报单元,设置字符串,以及音调、音量、语速等参数。
    • AVSpeechSynthesizer。语音合成器,将创建的AVSpeechUtterance对象添加到此对象的播报队列即可开始播报。

    下面展示下如何播报一段文本。

    先创建一个语音合成器:

    _synthesizer = [[AVSpeechSynthesizer alloc] init];
    

    再选择需要使用的语音:

    _voices = @[[AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"], [AVSpeechSynthesisVoice voiceWithLanguage:@"en-GB"]];
    

    注意所选的语音要跟文本所使用的语言匹配。比如,文本是英语,那你可以选择美式英语发音也可以选择英式英语发音,但是不能选择中文发音。

    最后我们将需要播报的文本创建成AVSpeechUtterance对象,并加入播报队列:

    - (void)buildSpeechStrings {
        _speechStrings = @[@"Hello AV Foundation. How are you?",
                           @"I'm well! Thanks for asking.",
                           @"Are you excited about the book?",
                           @"Very! I have always felt so misunderstood.",
                           @"What's your favorite feature?",
                           @"Oh, they're all my babies.  I couldn't possibly choose.",
                           @"It was great to speak with you!",
                           @"The pleasure was all mine!  Have fun!"];
    }
    
    - (void)beginConversation {
        for (NSInteger index = 0; index < self.speechStrings.count; index++) {
            AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithAttributedString:self.speechStrings[index]];
            // 设置语音
            utterance.voice = self.voices[index % 2];
            // 设置速率
            utterance.rate = AVSpeechUtteranceDefaultSpeechRate;
            // 设置语调
            utterance.pitchMultiplier = 0.8;
            // 设置音量
            utterance.volume = 0.7;
            // 播报前停顿
            utterance.preUtteranceDelay = 0.1;
            // 播报后停顿
            utterance.postUtteranceDelay = 0.1;
            [self.synthesizer speakUtterance:utterance];
        }
    }
    

    这样就开始播报给定文本了。

    需要注意的是只要utterance对象使用speakUtterance:对象加入到播报队列,其语调等各项参数就无法修改了,不管是正在播报,还是在等待播报中。

    你可以在Demo中尝试修改参数:https://gitee.com/sergeant/AVSpeech_Glance
    Demo源自《AV Foundation 开发秘籍》,主要修改的地方是尝试在播报中修改语调等参数,结论是无效。

    相关文章

      网友评论

          本文标题:iOS 文本转语音

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