我正在檢測麥克風打擊並使用它觸發動畫並獲取此錯誤消息。在初始化之前使用「常量」錯誤「。這是我的代碼:初始化之前使用的常量'錯誤'
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])
在此先感謝!
看起來像@ScottThompson你有覆蓋。只是一個提示,因爲它看起來像你是新來的Swift,強制解包一個可選的(* var *!)應該只能在你的應用程序崩潰的情況下完成,如果該變量爲零。 – PeejWeej