我想从 iPhone 麦克风获取原始音频数据(NSData 格式)以通过套接字进行流式传输。这不是我可以使用 twilio/etc 的情况,因为它是一个研究项目。套接字实现已完成(我可以发送音频文件),但我在获取流式麦克风数据时遇到问题。
这是我的尝试:
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
}
}
问题:
任何帮助表示赞赏。
Cheers
Your AVCaptureSession
超出范围并被释放。这就是为什么您的代表没有被召集的原因。您可以通过移动来解决此问题session
班级范围:
class ViewController: UIViewController, AVCaptureAudioDataOutputSampleBufferDelegate {
let session = AVCaptureSession()
override func viewDidLoad() {
一旦你有了音频CMSampleBuffer
,您可以将音频数据复制到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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)