AVSpeech Record/Save as Audio File

Hi there


I am trying to get AVSpeechSynthesizer to produce an AVSpeechUtterenace which I can record, so that I can use it for a local notification sound alert. Is there a way of doing this? I've been playing around with AVAudioUnits but not had any luck.


Thanks

import UIKit
import AVFoundation

#warning("This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's Info.plist must contain an NSMicrophoneUsageDescription key with a string value explaining to the user how the app uses this data.")

// Info.plist             Privacy - Microphone Usage Description              This app use the microphone to record audio

// Note: You may need a different AVAudioSession.Mode and a different AVAudioSession.CategoryOptions

class RecordAudioViewController: UIViewController {
    
    let session = AVAudioSession.sharedInstance()
    var audioRecorder: AVAudioRecorder?
    let synthesizer = AVSpeechSynthesizer()
    
    lazy var speechUtterance : AVSpeechUtterance = {
        let string = "Hello World!"
        let utterance = AVSpeechUtterance(string: string)
        utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
        return utterance
    }()
    
    private func speak(){
        print("\(type(of: self)) \(#function)")
        synthesizer.delegate = self
        synthesizer.speak(speechUtterance)
    }
    
    private func recordAudio() {
        print("\(type(of: self)) \(#function)")
        session.requestRecordPermission { [weak self] (granted) in
            guard granted else {
                return
            }
            
            guard let strongSelf = self else {
                return
            }
            
            do {
                try strongSelf.session.setCategory(.playAndRecord, mode:.spokenAudio, options: [.defaultToSpeaker])
                
                try strongSelf.session.setActive(true)
                
                let recordingFileName = "recording.m4a"
                let recordingURL = strongSelf.documentsDirectoryURL().appendingPathComponent(recordingFileName)
                
                let settings: [String : Any] = [
                    AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
                    AVSampleRateKey: 12000.0,
                    AVNumberOfChannelsKey: 1,
                    AVFormatIDKey: Int(kAudioFormatMPEG4AAC)
                ]
                
                try strongSelf.audioRecorder = AVAudioRecorder(
                    url: recordingURL,
                    settings: settings
                )
                strongSelf.audioRecorder?.record()
            }catch let error {
                print("error recordAudio: \(error)")
            }
        }
    }
    
    private func documentsDirectoryURL() -> URL {
        print("\(type(of: self)) \(#function)")
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return urls[urls.count-1]
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        recordAudio()
        speak()
    }
}

extension RecordAudioViewController : AVSpeechSynthesizerDelegate {
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        print("\(type(of: self)) \(#function)")
        audioRecorder?.stop()
    }
}
AVSpeech Record/Save as Audio File
 
 
Q