Skip to main content
 首页 » 操作系统

ios之为什么我需要为音频创建一个 sharedInstance

2024年01月01日75telwanggs

在我的代码中,我初始化了两个单例。我有 var session = AVAudioSession.sharedInstance 和 var audioSession = AVAudioSession.sharedInstance。然后我为第二个单例 setActive(false)。为什么我需要创建第二个?为什么我不能将第一个单例设置为 setActive(false) 而不是创建第二个单例?

我相信这是因为单例的每个类只能有一个实例;然而,我只是关闭了 Audio Session ,所以我不明白为什么我需要两个单例来做这件事。

@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) 
} 
} 

请您参考如下方法:

AVAudioSession是一个单例进程,不能播放(或录制)2 个不同的音频。 如果您从您的应用程序启动音频,正在运行的音频(就像您正在听音乐一样)将暂停。 为什么不只创建一个(可能是 class)variable 来管理 AVAudiosession?

如果你创建变量 2 次,它里面有相同的东西(因为单例总是返回相同的实例)。