AVSpeechSynthesizer output as file?

心不动则不痛 提交于 2019-11-28 04:13:44

问题


AVSpeechSynthesizer has a fairly simple API, which doesn't have support for saving to an audio file built-in.

I'm wondering if there's a way around this - perhaps recording the output as it's played silently, for playback later? Or something more efficient.


回答1:


As of now AVSpeechSynthesizer does not support this . There in no way get the audio file using AVSpeechSynthesizer . I tried this few weeks ago for one of my apps and found out that it is not possible , Also nothing has changed for AVSpeechSynthesizer in iOS 8.

I too thought of recording the sound as it is being played , but there are so many flaws with that approach like user might be using headphones, the system sound might be low or mute , it might catch other external sound, so its not advisable to go with that approach.




回答2:


This is finally possible, in iOS 13 AVSpeechSynthesizer now has write(_:toBufferCallback:):

let synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: "test 123")
utterance.voice = AVSpeechSynthesisVoice(language: "en")
var output: AVAudioFile?

synthesizer.write(utterance) { (buffer: AVAudioBuffer) in
   guard let pcmBuffer = buffer as? AVAudioPCMBuffer else {
      fatalError("unknown buffer type: \(buffer)")
   }
   if pcmBuffer.frameLength == 0 {
     // done
   } else {
     // append buffer to file
     if output == nil { 
       output = AVAudioFile(
         forWriting: URL(fileURLWithPath: "test.caf"), 
         settings: pcmBuffer.format.settings, 
         commonFormat: .pcmFormatInt16, 
         interleaved: false) 
     }
     output?.write(from: pcmBuffer)
   } 
}



回答3:


You can use OSX to prepare AIFF files (or, maybe, some OSX-based service) via NSSpeechSynthesizer method startSpeakingString:toURL:



来源:https://stackoverflow.com/questions/25965601/avspeechsynthesizer-output-as-file

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