OBJC AVSpeechUtterance writeUtterance how?

[亡魂溺海] 提交于 2021-01-29 16:16:50

问题


I am trying to create a TTS to file in Objc. Since iOS13 can write it to a file. But I'm stuck with writeUtterance:toBufferCallback.

Do someone has an exemple with this function in objc?

[synth speakUtterance:utterance];


回答1:


Referring to the potential answer in Swift, this would be the Objective-C implementation

AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc] init];
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:@"test 123"];
AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"];
[utterance setVoice:voice];

__block AVAudioFile *output = nil;

[synthesizer writeUtterance:utterance
           toBufferCallback:^(AVAudioBuffer * _Nonnull buffer) {
    AVAudioPCMBuffer *pcmBuffer = (AVAudioPCMBuffer*)buffer;
    if (!pcmBuffer) {
        NSLog(@"Error");
        return;
    }
    if (pcmBuffer.frameLength != 0) {
        //append buffer to file
        if (output == nil) {
            output = [[AVAudioFile alloc] initForWriting:[NSURL fileURLWithPath:@"test.caf"]
                                                settings:pcmBuffer.format.settings
                                            commonFormat:AVAudioPCMFormatInt16
                                             interleaved:NO error:nil];
        }
        [output writeFromBuffer:pcmBuffer error:nil];
    }
}];


来源:https://stackoverflow.com/questions/61969696/objc-avspeechutterance-writeutterance-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!