Ios录制Live mic数据无法录制并发送?

时间:2018-06-18 20:51:52

标签: ios iphone swift

import UIKit
import AVFoundation

class RecViewController: UIViewController,AVCaptureAudioDataOutputSampleBufferDelegate {

    @IBOutlet weak var recBtn: UIButton!

    let session = AVCaptureSession()
    var result: NSData?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.recBtn.setTitle("RECORDING", for: .normal)
    }

    @IBAction func recBtnAction(_ sender: Any) {

        session.sessionPreset = .medium

        let mic = AVCaptureDevice.default(for: .audio)
        var mic_input: AVCaptureDeviceInput!

        let audio_output = AVCaptureAudioDataOutput()
        audio_output.setSampleBufferDelegate(self, queue: DispatchQueue.main)

        do {
            mic_input = try AVCaptureDeviceInput(device: mic!)
        } catch {
            return
        }

        if session.inputs.isEmpty {
            self.session.addInput(mic_input)
            session.addOutput(audio_output)
        }

        session.startRunning()

    }
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {

        let block = CMSampleBufferGetDataBuffer(sampleBuffer)
        var length = 0
        var data: UnsafeMutablePointer<Int8>? = nil

        var status = CMBlockBufferGetDataPointer(block!, 0, nil, &length, &data)    // TODO: check for errors

        result = NSData(bytesNoCopy: data!, length: length, freeWhenDone: false)
    }

    @IBAction func playBtnAction(_ sender: Any) {
        // Storing the ns data and trying to play with following code but it dosent play cant hear a thing
        do {
            let audioPlayer = try AVAudioPlayer(data: result as! Data )
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch {
            print("Error")
        }
    }

}

我正在使用此代码从麦克风录制实时数据但是当我按下录制按钮时没有任何事情它既没有记录也没有委托和打印所以如何解决这个问题? (解决)

我已经更新了代码,当我试图通过AV音频播放器播放ns数据时,它不会播放任何如何解决这个问题的方法吗?

1 个答案:

答案 0 :(得分:1)

audio_output方法范围之外的任何内容实际上都不会保留recBtnAction。您离开方法时很可能会丢弃您的会话,因此不会为您捕获任何内容。

修改

使用您提供的示例代码进行游戏后,您的实际问题似乎是您使用的委托方法签名错误。

应该是:

func captureOutput(_ output: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
}