iOS - 录制音频5秒钟

时间:2015-05-22 21:47:04

标签: ios swift avaudiorecorder

我正在尝试使用AVAudioRecorder的方法recordForDuration录制5秒的音频。 出于某种原因,这似乎根本不起作用。

附加的audioRecorderDidFinishRecording不会被调用。 为了使它更好,屏幕顶部的红色棉绒只出现在很短的时间内,因此它甚至不能录制5秒钟。

我做错了什么?

class ViewController: UIViewController, AVAudioRecorderDelegate {
    //...
    func micTest(){
        var audioSession:AVAudioSession = AVAudioSession.sharedInstance()
        audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
        audioSession.setActive(true, error: nil)

        var documents: AnyObject = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory,  NSSearchPathDomainMask.UserDomainMask, true)[0]
        var str =  documents.stringByAppendingPathComponent("recordTest.caf")
        var url = NSURL.fileURLWithPath(str as String)

        var recordSettings = [AVFormatIDKey:kAudioFormatAppleIMA4,
            AVSampleRateKey:44100.0,
            AVNumberOfChannelsKey:2,AVEncoderBitRateKey:12800,
            AVLinearPCMBitDepthKey:16,
            AVEncoderAudioQualityKey:AVAudioQuality.Max.rawValue
        ]
        var error: NSError?

        var audioRecorder = AVAudioRecorder(URL:url, settings: recordSettings as [NSObject : AnyObject], error: &error)
        audioRecorder.delegate = self;
        if error != nil {
            println(error!.localizedDescription)
        } else {
            audioRecorder.recordForDuration(NSTimeInterval(5.0))
        }
    }

    func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) {
        println("recording finished");
    }
}

0 个答案:

没有答案