ios - 为什么我需要声明一个 AVAudioSession 实例?

标签 ios swift avfoundation

@IBAction func recordAudio(sender: UIButton) {
recodingLabel.hidden = false
stopButton.hidden = false


let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String

    let currentDateTime = NSDate()
    let formatter = NSDateFormatter()
    formatter.dateFormat = "ddMMyyyy-HHmmss"

    let recordingName = formatter.stringFromDate(currentDateTime)+".wav"

    let pathArray = [dirPath,recordingName]

    let filePath = NSURL.fileURLWithPathComponents(pathArray)
    //println(filePath)

  var recordSession = AVAudioSession.sharedInstance()
  recordSession.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)

  audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error: nil)
  audioRecorder.delegate = self
  audioRecorder.meteringEnabled = true
  audioRecorder.record()

}

从上面的代码可以看出,我正在尝试通过按下按钮来录制用户的音频,并希望在下一个 View 中播放相同的内容。

我遇到的问题是以下代码块:

var recordSession = AVAudioSession.sharedInstance()
recordSession.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)

为什么我需要声明上面的代码块?当我注释掉并运行该应用程序时,没有任何区别。

以上代码来自优达学城类(class)

最佳答案

音频是设备上的共享资源。让系统知道您打算使用音频做什么的原因是帮助它协调您的使用与正在发生的其他事情。例如,如果电话在录音过程中响起,或者用户选择了不同的麦克风,您的 App 会发生什么情况?这些和其他交互由全局 AVAudioSession 对象处理。

关于ios - 为什么我需要声明一个 AVAudioSession 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29583472/

相关文章:

javascript - iOS 上的 Photoswipe 图库关闭事件

ios - SpeechKit 转录音频文件

ios - GoogleMaps cocoapod 中缺少 GMSPlace viewport 成员

iphone - 如何在 iPhone 中使用 URL 链接播放音乐文件?

swift - 我的相机应用程序 Swift 代码中有几个错误

ios - 基于 UITextField 中文本的响应式(Reactive) Cocoa 启用按钮

ios - 如何在具有两个 Storyboard iOS Swift 的项目中初始化 View Controller

带有数字签名的 Swift 签名字符串

ios - AVFoundation 捕获视频 iOS sdk `AVCaptureMovieFileOutput ` 并写入服务器

ios - 从沙箱切换后,推送通知在生产环境中不起作用