The same happens on iOS 14.6. The code below produces a very noisy audio file.
let speechSynthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: "Hi, my name is ALex.")
let voice = AVSpeechSynthesisVoice(identifier: "com.apple.speech.voice.Alex")!
utterance.voice = voice
let audioFileSettings = voice.audioFileSettings
let audioUrl = ... //valid URL
var audioFile = try! AVAudioFile(forWriting: audioUrl, settings: audioFileSettings, commonFormat: .pcmFormatInt32, interleaved: false)
speechSynthesizer.write(utterance) { buffer in
let pcmBuffer = buffer as! AVAudioPCMBuffer
if pcmBuffer.frameLength > 0{
try! audioFile.write(from: pcmBuffer)
}
}
On some voices (example: Alex), it happens, and on others (example: Samantha), it doesn't.
The code is so simple that I don't think there is a bug there. It must be a framework problem. Mr. Frameworks Engineer, fix this, please.