OBJC AVSpeechUtterance writeUtterance 怎么样?

OBJC AVSpeechUtterance writeUtterance how?

我正在尝试创建一个 TTS 以在 Objc 中归档。 由于 iOS13 可以将其写入文件。 但我坚持 writeUtterance:toBufferCallback.

有人在 objc 中有这个函数的例子吗?

[synth speakUtterance:utterance];

Referring to the potential answer in Swift,这将是 Objective-C 实现

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];
    }
}];