Swift 2:AVFoundation录制实时音频样本

时间:2015-10-20 19:16:59

标签: ios audio avfoundation swift2 recording

我试图通过AVFoundation听微信如下,不幸的是,尽管我的代表被调用,我根本没有得到任何样本。 我无法找到我的错误所在。

我的代码如下。

设置

let captureAudioSession = AVCaptureSession()


func startRealtimeAudioRecording() {


    let devices = AVCaptureDevice.devices()

    var captureDevice:AVCaptureDevice? = nil

    // Loop through all the capture devices on this phone
    for device in devices {
        // Make sure this particular device supports video
        if device.hasMediaType(AVMediaTypeAudio) {
            captureDevice = device as? AVCaptureDevice
            if captureDevice != nil {
                print("Capture audio device found")
                break
            }
        }
    }


    if let device = captureDevice {    //AVCaptureDevice(uniqueID: AVMediaTypeAudio)
        do {
            let input = try AVCaptureDeviceInput(device: device)
            captureAudioSession.addInput(input)
        }
        catch let error {
            NSLog("*** Error in startRealtimeAudioRecording(): \(error)")
            return
        }

        let output = AVCaptureAudioDataOutput()
        let queue = dispatch_queue_create("Sample callback", DISPATCH_QUEUE_SERIAL)
        output.setSampleBufferDelegate(self, queue:queue)
        captureAudioSession.addOutput(output)
        captureAudioSession.startRunning()
    }
}

代表我没有打印样本的地方:

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {

    var audioBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))

    let audioBuffers = UnsafeBufferPointer<AudioBuffer>(start: &audioBufferList.mBuffers, count: Int(audioBufferList.mNumberBuffers))

    var i = 0

    for audioBuffer in audioBuffers {
        let samples = UnsafeMutableBufferPointer<Float>(start: UnsafeMutablePointer<Float>(audioBuffer.mData), count: Int(audioBuffer.mDataByteSize) / sizeof(Float))

        if samples.count > 0 {
            print("Bufffer \(i++):")

            for sample in samples {
                print(sample)
            }
        }
    }
}

0 个答案:

没有答案