AVSpeechSynthesizer utterance to audio file

橙三吉。 提交于 2019-11-30 11:24:05

It is possible to record audio generated by your app (not from other apps). Although AVSpeech does not provide an API to save the generated audio, Apple has other APIs that can do the job. The solution is probably not as clean as you would like, but it should work.

Apple provides a framework called the Audio Unit Framework to manage advanced audio processing and recording. This is the only Framework in the iOS SDK (to my knowledge) that can play and record audio simultaneously. The Audio Unit Hosting Guide looks promising, and so does the Audio Mixer Sample App.

Note: I have not tried using the Audio Unit Framework with AVSpeechSynthesizer (it may or may not work). However, considering AVSpeechSynthesizer plays nice with CoreAudio then it is more than likely it will work with AudioUnits.


If the above solution does not work, then a simple workaround may do the trick. AVSpeechSynthesizer does not require any network connection to properly function, so in many cases you may not need to save the audio. Instead you could save the text for later using NSFileManager:

NSString *textToSynthesize = @"Just what do you think you are doing, Dave?";

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths firstObject];

[textToSynthesize writeToFile:[documentsDirectory stringByAppendingPathComponent:@"synthText.txt"] atomically:YES encoding:NSUTF8StringEncoding error:&error];

When you are ready to synthesize the text, just read it from the file and plug it back into the AVSpeechSynthesizer. I do realize that this solution will not work or apply in all cases (e.g. if you need to send the audio file to someone).


Those are just a few possible solutions for the issue, both of which are workarounds and may or may not work depending on your specific scenario. YMMV. Good luck!

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