iOS 直播-获取音频(视频)数据
//
// ViewController.m
// capture-test
//
// Created by caoxu on 16/6/3.
// Copyright © 2016年 caoxu. All rights reserved.
//
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<AVCaptureAudioDataOutputSampleBufferDelegate>
@property (nonatomic, strong) AVCaptureSession * session;
@property (nonatomic, strong) AVCaptureAudioDataOutput *audioOutput;
@property (nonatomic, strong) dispatch_queue_t audioQueue;
@property (nonatomic, strong) AVCaptureConnection *audioConnection;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.session = [[AVCaptureSession alloc]init];
NSError *error = nil;
AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (error) {
NSLog(@"Error getting video input device: %@", error.description);
}
if ([self.session canAddInput:audioInput]) {
[self.session addInput:audioInput];
}
// 配置采集输出,即我们取得音频的接口
self.audioQueue = dispatch_queue_create("Audio Capture Queue", DISPATCH_QUEUE_SERIAL);
self.audioOutput = [[AVCaptureAudioDataOutput alloc] init];
[self.audioOutput setSampleBufferDelegate:self queue:self.audioQueue];
if ([self.session canAddOutput:self.audioOutput]) {
[self.session addOutput:self.audioOutput];
}
// 保存Connection,用于在SampleBufferDelegate中判断数据来源(是Video/Audio?)
self.audioConnection = [self.audioOutput connectionWithMediaType:AVMediaTypeAudio];
[self.session startRunning];
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
// 这里的sampleBuffer就是采集到的数据了,但它是Video还是Audio的数据,得根据connection来判断
if (connection == self.audioConnection) { // Audio
NSLog(@"%@",sampleBuffer);
NSLog(@"这里获得audio sampleBuffer,做进一步处理(编码AAC)");
}
}
@end