获取iPhone的麦克风数据通过套接字stream
我想从iPhone麦克风(NSData格式)获取原始audio数据通过套接字stream。 这不是我可以使用twilio / etc的情况,因为这是一个研究项目。 套接字的实现已经完成(我可以发送audio文件),但我无法获得stream式麦克风数据。
这是我的尝试:
class ViewController: UIViewController, AVCaptureAudioDataOutputSampleBufferDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.setupMicrophone() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupMicrophone() { let session = AVCaptureSession() session.sessionPreset = AVCaptureSessionPresetMedium let mic = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio) var mic_input: AVCaptureDeviceInput! let audio_output = AVCaptureAudioDataOutput() audio_output.setSampleBufferDelegate(self, queue: dispatch_get_main_queue()) do { mic_input = try AVCaptureDeviceInput(device: mic) } catch { return } session.addInput(mic_input) session.addOutput(audio_output) session.startRunning() } func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) { // Do something here } }
问题:
-
委托function从未被调用。
-
给委托的数据(如果被调用的话)不是NSData,还有另外一个函数可以提供NSData吗? 有没有办法将CMSampleBuffer转换为NSData?
任何帮助表示赞赏。
干杯
您的AVCaptureSession
超出范围并被释放。 这就是为什么你的委托没有被调用。 您可以通过将会话移至类范围来解决此问题:
class ViewController: UIViewController, AVCaptureAudioDataOutputSampleBufferDelegate { let session = AVCaptureSession() override func viewDidLoad() {
一旦你有一个audioCMSampleBuffer
,你可以将audio数据复制到一个NSData
对象,如下所示:
let block = CMSampleBufferGetDataBuffer(sampleBuffer) var length = 0 var data: UnsafeMutablePointer<Int8> = nil let status = CMBlockBufferGetDataPointer(block!, 0, nil, &length, &data) // TODO: check for errors let result = NSData(bytes: data, length: length)
如果你小心,并希望避免复制,你可以使用NSData(bytesNoCopy: data, length: length, freeWhenDone: false)
- 缺少项目中Xcode生成的必需模块’SwiftShims’错误
- iOS模拟器和实时代码重新加载-React Native
- 当应用程序崩溃时,“applicationWillTerminate”或“applicationDidEnterBackground”被调用?
- 只有一个(自定义)注释从其他注释数组中旋转
- 如何在iOS中绕过itms-services://?action = download-manifest UIAlertView?
- stopRangingBeaconsInRegion可能会停止监视区域的通知?
- 对不同的构buildscheme使用不同的GoogleService-Info.plist
- iOS:XMPP:群聊消息的消息归档
- 寻找iOS中所有可用语言的列表