iOS 直播 獲取音頻(視頻)數據 ` ` ...
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