Ios 常数';错误';在初始化之前使用
我检测到麦克风的响声,并用它来触发一个动画,我得到了这个错误信息。“初始化前使用的常量“错误”。这是我的代码:Ios 常数';错误';在初始化之前使用,ios,swift,error-handling,constants,avaudiorecorder,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.sharedInsta
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])
提前谢谢 您没有可以在声明点和使用点之间设置
error
值的代码。对于可能采用新值的错误,必须将其传递给AVAudioRecorder
的构造函数。您可以使用以下命令初始化错误:
let错误:错误?=无
但这同样是无足轻重的,因为它的值不可能改变(它是一个let
变量),即使它是一个var,在声明它和在if let
构造中使用它之间,它也不会传递给任何代码
您正在崩溃,因为您告诉系统您要创建AVAudioRecorder,但它永远不会失败(即尝试!
)。您更可能希望执行以下操作:
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...
}
您没有可以在声明点和使用点之间设置
error
值的代码。对于可能采用新值的错误,必须将其传递给AVAudioRecorder
的构造函数。您可以使用以下命令初始化错误:
let错误:错误?=无
但这同样是无足轻重的,因为它的值不可能改变(它是一个let
变量),即使它是一个var,在声明它和在if let
构造中使用它之间,它也不会传递给任何代码
您正在崩溃,因为您告诉系统您要创建AVAudioRecorder,但它永远不会失败(即尝试!
)。您更可能希望执行以下操作:
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...
}
看来@Scotthompson已经把你掩护起来了。看来@Scotthompson已经把你掩护起来了。好的,谢谢,我现在在NSLog中收到一条消息:无法将NSPathSotre2的值类型强制转换为NSUrl。你对我在这方面做错了什么有什么建议吗?”录音机=试试!AVAudioRecorder(url:(documents)as!url,settings:recordSettings as![String:Any])尝试我在答案中编辑的最新更新的代码示例。好的,谢谢,我现在在NSLog中收到一条消息:无法将NSPathSotre2的值类型强制转换为NSUrl。你对我在这方面做错了什么有什么建议吗?”录音机=试试!AVAudioRecorder(url:(documents)as!url,settings:recordSettings as![String:Any])试试我在答案中编辑的最新代码示例。