syedhali/EZAudio

EZAudio doesnt work: Thread1 EXC_BAD_ACCESS

kunass2 opened this issue · 1 comments

My complete implementation of EZAudio:

class ViewController: UIViewController, EZMicrophoneDelegate, EZRecorderDelegate {

    @IBOutlet var recordingAudioPlot: EZAudioPlot!

    private var isRecording = false {
    
        didSet {

            if isRecording {
            
                player.pause()
                recordingAudioPlot.clear()
                microphone.startFetchingAudio()
                recorder = EZRecorder(url: filePathUrl(), clientFormat: microphone.audioStreamBasicDescription(), fileType: EZRecorderFileType.M4A, delegate: self) 
                // ** Here is where the error occurs **
            
            } else {
            
                recorder.delegate = nil
                microphone.stopFetchingAudio()
                recorder.closeAudioFile()
            
                player.playAudioFile(EZAudioFile(url: filePathUrl()))
            }
        }
    }
    private var microphone = EZMicrophone()
    private var recorder = EZRecorder()
    private var player = EZAudioPlayer()

    @IBAction func startStopRecordingButtonTapped(_ sender: UIButton) {
        isRecording = !isRecording
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let session = AVAudioSession.sharedInstance()
        try! session.setCategory(AVAudioSessionCategoryPlayAndRecord)
        try! session.setActive(true)
    
        microphone.delegate = self
    
        try! session.overrideOutputAudioPort(.speaker)
    }

    func microphone(_ microphone: EZMicrophone!, hasAudioReceived buffer: UnsafeMutablePointer<UnsafeMutablePointer<Float>?>!, withBufferSize bufferSize: UInt32, withNumberOfChannels numberOfChannels: UInt32) {
    
        DispatchQueue.main.async {
            self.recordingAudioPlot.updateBuffer(buffer[0], withBufferSize: bufferSize)
        }
    }

    func microphone(_ microphone: EZMicrophone!, hasBufferList bufferList: UnsafeMutablePointer<AudioBufferList>!, withBufferSize bufferSize: UInt32, withNumberOfChannels numberOfChannels: UInt32) {
    
        if isRecording {
            recorder.appendData(from: bufferList, withBufferSize: bufferSize)
        }
    }

    private func filePathUrl() -> URL {
    
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
    
        return URL(fileURLWithPath: String(format: "%@/%@", path, "pathtofile.m4a"))
    }
}

The error is following:

enter image description here
What goes wrong?

imagine you have a microphone and no recorder.
Then you start to sing a song and the tape is not in the recorder yet.
You hit record.. well.. BAD_ACCESS..

first setting up the recorder, then start fetching the audio.
A specially when your microphone delegate method is pushing the received buffer to a recorder that is not running yet.