ios – 使用AVAudioRecorder录制语音

我正在尝试制作一个简单的录音机.我正在使用
Xcode-beta 7,而且我的代码基于这三个来源.

> AVFoundation Audio Recording With Swift
> AVAudioRecorder Reference查看初始化器的输入.
> Recording audio in Swift获取我应该使用的设置

我正在使用以下代码:

var recordSettings = [
        AVFormatIDKey: kAudioFormatAppleIMA4,
        AVLinearPCMIsBigEndianKey: 0,
        AVLinearPCMIsFloatKey: 0,
        AVNumberOfChannelsKey: 2,
        AVSampleRateKey: 32000
    ]

    var session = AVAudioSession.sharedInstance()

    do{
        try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
        recorder = AVAudioRecorder(URL: filePath, settings: recordSettings, error: nil)
    }catch{
        print("Error")
    }

但它说“找不到类型为’AVAudioRecorder’的初始值设定项接受类型’的参数列表'(URL:NSURL?,设置:[String:AudioFormatID],错误:nil)’”

我的输入不是文档所要求的吗?

最佳答案 AVAudioRecorder不再需要error参数:

init(URL url: NSURL, settings settings: [String : AnyObject]) throws

此外,我需要解开filePath,如上一个答案所示:

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

    let recordingName = "my_audio.wav"
    let pathArray = [dirPath, recordingName]
    let filePath = NSURL.fileURLWithPathComponents(pathArray)
    let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue,
            AVEncoderBitRateKey: 16,
            AVNumberOfChannelsKey: 2,
            AVSampleRateKey: 44100.0]
    print(filePath)

    let session = AVAudioSession.sharedInstance()
    do {
        try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
        audioRecorder = try AVAudioRecorder(URL: filePath!, settings: recordSettings as! [String : AnyObject])
    } catch _ {
        print("Error")
    }

    audioRecorder.delegate = self
    audioRecorder.meteringEnabled = true
    audioRecorder.prepareToRecord()
    audioRecorder.record()
}
点赞