不断的错误'在初始化之前使用

时间:2017-05-01 22:30:55

标签: ios swift error-handling constants avaudiorecorder

我正在检测麦克风,并使用它来触发动画并收到此错误消息。 "常数'错误'在被初始化之前使用"。这是我的代码:

    override func viewDidLoad() {
    super.viewDidLoad()

    //make an AudioSession, set it to PlayAndRecord and make it active
    let audioSession:AVAudioSession = AVAudioSession.sharedInstance()
    try! audioSession.setCategory(AVAudioSessionCategoryRecord)
    try! audioSession.setActive(true)

    //set up the URL for the audio file
    let documents: AnyObject = NSSearchPathForDirectoriesInDomains( FileManager.SearchPathDirectory.documentDirectory,  FileManager.SearchPathDomainMask.userDomainMask, true)[0] as AnyObject
    let str = (documents as! NSString).appending("recordTest.caf")
    NSURL.fileURL(withPath: str as String)


    // make a dictionary to hold the recording settings so we can instantiate our AVAudioRecorder
    let recordSettings: [NSObject : AnyObject] = [AVFormatIDKey as NSObject:kAudioFormatAppleIMA4 as AnyObject,
                                                  AVSampleRateKey as NSObject:44100.0 as AnyObject,
                                                  AVNumberOfChannelsKey as NSObject:2 as AnyObject,AVEncoderBitRateKey as NSObject:12800 as AnyObject,
                                                  AVLinearPCMBitDepthKey as NSObject:16 as AnyObject,
                                                  AVEncoderAudioQualityKey as NSObject:AVAudioQuality.max.rawValue as AnyObject

    ]

    //declare a variable to store the returned error if we have a problem instantiating our AVAudioRecorder
    let error: NSError?

    //Instantiate an AVAudioRecorder
    recorder = try! AVAudioRecorder(url: documents as! URL, settings: recordSettings as! [String : Any])

    //If there's an error, print it - otherwise, run prepareToRecord and meteringEnabled to turn on metering (must be run in that order)
    if let e = error {
        print(e.localizedDescription)
    } else {
        recorder.prepareToRecord()
        recorder.isMeteringEnabled = true

        //start recording
        recorder.record()

        //instantiate a timer to be called with whatever frequency we want to grab metering values
        self.levelTimer = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(ViewController.levelTimerCallback), userInfo: nil, repeats: true)

    }

}

//selector/function is called every time our timer (levelTime) fires
func levelTimerCallback() {
    //update meters
    recorder.updateMeters()

    //print to the console if we are beyond a threshold value
    if recorder.averagePower(forChannel: 0) > -7 {
        print("Mic Blow Detected ")
        print(recorder.averagePower(forChannel: 0))
        isAnimating = false
    } else {
        isAnimating = true
    }
}

似乎这条线正在迫使应用程序退出,所以很明显这是问题的所在,但我是Xcode的新手并且无法发现我做错了什么,如果有人对我应该改变这一点有什么想法那么会很好。

recorder = try! AVAudioRecorder(url: documents as! URL, settings: recordSettings as! [String : Any])

提前致谢!

1 个答案:

答案 0 :(得分:1)

您没有可以在声明它的点与使用它之间设置error值的代码。如果错误可能采用新值,则必须将其传递给AVAudioRecorder的构造函数。您可以使用以下命令初始化错误:

let error : Error? = nil

但是这又是无聊的,因为没有机会改变它的值(它是一个let变量),即使它是一个var,它也不会在声明它之间传递给任何代码当它在if let构造中使用时。

你崩溃是因为你告诉系统你要创建AVAudioRecorder但它永远不会失败(那是try!)。你更有可能想做类似的事情:

let documentSearchPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDir = documentSearchPaths[0] as NSString
let recordingFilePath = documentsDir.appendingPathComponent("recordTest.caf")
let recordingFileURL = NSURL.fileURL(withPath: recordingFilePath)

var recorder : AVAudioRecorder?
do{
    let audioSession = AVAudioSession.sharedInstance()
    try audioSession.setCategory(AVAudioSessionCategoryRecord)
    try audioSession.setActive(true)

    // make a dictionary to hold the recording settings so we can instantiate our AVAudioRecorder
    let recordSettings: [String : Any] = [AVFormatIDKey : kAudioFormatAppleIMA4,
                                          AVSampleRateKey : NSNumber(value: 44100.0),
                                          AVNumberOfChannelsKey : NSNumber(value: 2),
                                          AVEncoderBitRateKey : NSNumber(value: 12800),
                                          AVLinearPCMBitDepthKey : NSNumber(value: 16),
                                          AVEncoderAudioQualityKey :NSNumber(value: AVAudioQuality.max.rawValue)
    ]

    recorder = try AVAudioRecorder(url: recordingFileURL, settings: recordSettings)
} catch let audio_error as NSError {
    print("Setting up the audio recording failed with error \(audio_error)")
}

if let recorder = recorder {
    recorder.prepareToRecord()
    recorder.isMeteringEnabled = true

    //start recording
    recorder.record()

    //etc...
}