TommyBs
TommyBs

Reputation: 9648

AVAudioRecorder - found nil when unwrapping optional

I'm currently trying to set-up an AVAudioRecorder to capture some user audio from the microphone on an iPhone, but I keep getting an 'unexpectedly found nil when unwrapping an optional' error.

I don't try to start the recording until the user taps a button and I've made sure I definitely have microphone permission.

My code is as follows and I can't see where I'm going wrong.recordTapped is the IBAction hooked unto the button and it's specifically when I try to instantiate the 'recorder' object that this crashes. AudioUrl is populated if I use a 'print' statement and settings is set, so I'm not sure what's going on here.

@IBAction func recordTapped() {
        if recorder == nil {
            startRecording()
        } else {
            finishRecording(success: true)
        }
    }

    func startRecording() {
        view.backgroundColor = UIColor(red: 0.6, green: 0, blue: 0, alpha: 1)

        recordButton.setTitle("Tap to Stop", forState: .Normal)

        let audioURL = ViewController.getAudioURL()
        let settings = [
            AVFormatIDKey: Int(kAudioFileMPEG4Type),
            AVSampleRateKey: 12000.0,
            AVNumberOfChannelsKey: 1 as NSNumber,
            AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue
        ]

        do {
            recorder = try AVAudioRecorder(URL: audioURL, settings: settings)
            recorder.prepareToRecord()

            recorder.delegate = self
            recorder.record()
        } catch {
            finishRecording(success: false)
        }
    }

    class func getDocumentsDirectory() -> NSString {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
        let documentsDirectory = paths[0]
        return documentsDirectory
    }

    class func getAudioURL() -> NSURL {
        let audioFilename = getDocumentsDirectory().stringByAppendingPathComponent("audio.m4a")
        let audioURL = NSURL(fileURLWithPath: audioFilename)

        return audioURL
    }

I found this question Swift, unwrapping nil runtime error for recording audio but nothing really seems applicable.

Edit: When I debug it pauses execution on the recorder = try AVAudioRecorder line and then goes to

libswiftCore.dylib`function signature specialization <Arg[0] = Exploded, Arg[1] = Exploded, Arg[2] = Dead, Arg[3] = Dead> of Swift._fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt) -> ():
    0x10027655c <+0>:   stp    x29, x30, [sp, #-16]!
    0x100276560 <+4>:   mov    x29, sp
    0x100276564 <+8>:   sub    sp, sp, #16               ; =16 
    0x100276568 <+12>:  and    w8, w2, #0x1
    0x10027656c <+16>:  tbnz   w8, #0, 0x10027658c       ; <+48>
    0x100276570 <+20>:  tbnz   x1, #63, 0x1002765c8      ; <+108>
    0x100276574 <+24>:  add    x1, x0, x1
    0x100276578 <+28>:  mov    x2, x3
    0x10027657c <+32>:  mov    x3, x4
    0x100276580 <+36>:  mov    x4, x5
    0x100276584 <+40>:  bl     0x1002be5b0               ; function signature specialization <Arg[0] = Exploded, Arg[1] = Exploded> of Swift.(_fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt) -> ()).(closure #2)
->  0x100276588 <+44>:  brk    #0x1

the output of 'bt' is as follows:

 * thread #1: tid = 0x71d9f5, 0x000000010036cfc0 libswiftCore.dylib`swift_willThrow, queue = 'com.apple.main-thread', stop reason = breakpoint 2.1
    frame #0: 0x000000010036cfc0 libswiftCore.dylib`swift_willThrow
    frame #1: 0x00000001000ec75c`AVAudioRecorder.__allocating_init(URL : NSURL, settings : [String : AnyObject]) throws -> AVAudioRecorder + 188 at ViewController.swift:0
  * frame #2: 0x00000001000ea480`ViewController.startRecording(self=0x000000015f664ac0) -> () + 1032 at ViewController.swift:112
    frame #3: 0x00000001000ea000`ViewController.recordTapped(self=0x000000015f664ac0) -> () + 164 at ViewController.swift:92
    frame #4: 0x00000001000ea064`@objc ViewController.recordTapped() -> () + 40 at ViewController.swift:0
    frame #5: 0x0000000188868be8 UIKit`-[UIApplication sendAction:to:from:forEvent:] + 100
    frame #6: 0x0000000188868b64 UIKit`-[UIControl sendAction:to:forEvent:] + 80
    frame #7: 0x0000000188850870 UIKit`-[UIControl _sendActionsForEvents:withEvent:] + 436
    frame #8: 0x0000000188868454 UIKit`-[UIControl touchesEnded:withEvent:] + 572
    frame #9: 0x0000000188868084 UIKit`-[UIWindow _sendTouchesForEvent:] + 804
    frame #10: 0x0000000188860c20 UIKit`-[UIWindow sendEvent:] + 784
    frame #11: 0x000000018883104c UIKit`-[UIApplication sendEvent:] + 248
    frame #12: 0x000000018882f628 UIKit`_UIApplicationHandleEventQueue + 6568
    frame #13: 0x000000018368909c CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
    frame #14: 0x0000000183688b30 CoreFoundation`__CFRunLoopDoSources0 + 540
    frame #15: 0x0000000183686830 CoreFoundation`__CFRunLoopRun + 724
    frame #16: 0x00000001835b0c50 CoreFoundation`CFRunLoopRunSpecific + 384
    frame #17: 0x0000000184e98088 GraphicsServices`GSEventRunModal + 180
    frame #18: 0x000000018889a088 UIKit`UIApplicationMain + 204
    frame #19: 0x00000001000ed528`main + 144 at AppDelegate.swift:12
    frame #20: 0x000000018314e8b8 libdyld.dylib`start + 4

UPDATE: So the initial crash was caused by the 'stopRecording' method which I didn't include. This was basically calling recorder.stop() even though recorder didn't exist. Problem solved with a simple nil check. Though this is still not working with the following error:

  Error Domain=NSOSStatusErrorDomain Code=1718449215 "(null)"

Which a quick google search informs me I am using invalid types for recording!

For anyone else looking at this, it then turns out I was using KAudioFile... instead of kAudioFormat in the settings for my recorder

thanks

Upvotes: 1

Views: 1794

Answers (1)

TommyBs
TommyBs

Reputation: 9648

For anyone else looking at this, it then turns out I was using KAudioFile... instead of kAudioFormat in the settings for my recorder

Upvotes: 1

Related Questions