1
在我的代码中,我初始化了两个单例。我有var session = AVAudioSession.sharedInstance
和var audioSession = AVAudioSession.sharedInstance
。我然后setActive(false)
第二个单身人士。为什么我需要创建第二个?为什么不能创建第一个单例到setActive(false)
?为什么我需要为音频创建一个sharedInstance?
我相信这是因为单身人士每班只能有一个实例;不过,我只是关闭音频会话,所以我不明白为什么我需要两个单身人士来做到这一点。
@IBAction func recordAudio(sender: UIButton) {
recordButton.enabled = false
stopButton.hidden = false
recordAudioOutlet.hidden = false
//Get a file path to store the audio recording
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let currentDateTime = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "ddMMyyyy-HHmmss"
let recordingName = formatter.stringFromDate(currentDateTime)
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
println(filePath)
//Setup audio session
var session = AVAudioSession.sharedInstance()
session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
//Initialize and prepare the recorder
audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error: nil)
audioRecorder.meteringEnabled = true
audioRecorder.record()
}
@IBAction func stopAudio(sender: UIButton) {
//Stop recording the user's voice
recordAudioOutlet.hidden = true
audioRecorder.stop()
var audioSession = AVAudioSession.sharedInstance();
audioSession.setActive(false, error: nil)
}
}
我不明白...你为什么认为你需要两个单身? – 2015-04-02 03:08:40
事实上,“两个单身”是一个非sequiter。 AVAudioSession.sharedInstance()总是返回一个实例 - 单例。不是两次调用'sharedInstance',你可以将第一次调用的引用保存在一个属性中,然后使用它,但是因为使用了局部变量,所以需要第二次获取该引用。 – Paulw11 2015-04-02 03:24:31
@ Paulw11听起来像将'sharedInstance'设置为全局属性而不是局部变量可以解决这个问题吗? – Michael 2015-04-02 04:11:13