Cocoa 如何将AVAudioRecorder声明为全局变量
我很难理解为什么我不能声明这里看到的记录器变量,因为它可用于类中的任何操作 编辑以完整显示仍显示相同行为的新测试项目。 我似乎无法在全球范围内声明记录器变量。见评论:Cocoa 如何将AVAudioRecorder声明为全局变量,cocoa,swift,avaudiorecorder,Cocoa,Swift,Avaudiorecorder,我很难理解为什么我不能声明这里看到的记录器变量,因为它可用于类中的任何操作 编辑以完整显示仍显示相同行为的新测试项目。 我似乎无法在全球范围内声明记录器变量。见评论: import Cocoa import AVFoundation @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, AVAudioRecorderDelegate { var recorder : AVAudioRecorder
import Cocoa
import AVFoundation
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, AVAudioRecorderDelegate {
var recorder : AVAudioRecorder = AVAudioRecorder() // remove this and clean up un-declared recorder vars, and it appears to record as expected
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
@IBAction func startRecording(sender: AnyObject) {
var recordSettings = [
AVFormatIDKey: kAudioFormatAppleLossless,
AVEncoderAudioQualityKey : AVAudioQuality.Medium.rawValue,
AVEncoderBitRateKey : 16,
AVNumberOfChannelsKey: 2,
AVSampleRateKey : 44100.0
]
var theRecordingUrl = "/Users/myMbp/Desktop/test.wav" // !!! #### ammend the url for testing #### !!!
var theRecordingUrlAsUrl = NSURL(string: theRecordingUrl)!
println(theRecordingUrlAsUrl) // still looks good before crash
var recorderError: NSError?
recorder = AVAudioRecorder(URL: theRecordingUrlAsUrl, settings: recordSettings, error: &recorderError) // with the global recorder var it crashes here
if let e = recorderError {
println(e.localizedDescription)
} else {
recorder.delegate = self
recorder.meteringEnabled = true
if recorder.prepareToRecord() {
println("recording prepared")
}else{
println("fialed to prepare recordeing")
}
if recorder.record() {
println("started recording")
}else{
println("fialed to start recordeing")
}
}
}
@IBAction func stopRecording(sender: AnyObject) {
recorder.stop()
}
}
大量的实验发现,答案是,我必须声明全局记录器变量,如下所示:
var recorder:AVAudioRecorder!