Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVSpeechSynthesizer output as file?

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.

like image 458
Andrew Avatar asked Sep 22 '14 01:09

Andrew


1 Answers

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)
   } 
}
like image 157
Jan Berkel Avatar answered Sep 20 '22 18:09

Jan Berkel