iOS RTMP 視頻直播開發筆記(1) – 采集攝像頭圖像


1. 采集硬件(攝像頭)視頻圖像

這里簡單說下 iOS 的攝像頭采集。

首先初始化AVCaptureSession,說到Session,有沒有人想到AVAudioSession呢?

	
// 初始化 AVCaptureSession
_session = [[AVCaptureSession alloc] init];

設置采集的 Video 和 Audio 格式,這兩個是分開設置的,也就是說,你可以只采集視頻。

// 配置采集輸入源(攝像頭)
NSError *error = nil;
// 獲得一個采集設備,例如前置/后置攝像頭
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// 用設備初始化一個采集的輸入對象
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
if (error) {
    NSLog(@"Error getting video input device: %@", error.description);
}
if ([_session canAddInput:videoInput]) {
    [_session addInput:videoInput]; // 添加到Session
}
 
// 配置采集輸出,即我們取得視頻圖像的接口
_videoQueue = dispatch_queue_create("Video Capture Queue", DISPATCH_QUEUE_SERIAL);
_videoOutput = [[AVCaptureVideoDataOutput alloc] init];
[_videoOutput setSampleBufferDelegate:self queue:_videoQueue];
 
// 配置輸出視頻圖像格式
NSDictionary *captureSettings = @{(NSString*)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA)};
 
_videoOutput.videoSettings = captureSettings;
_videoOutput.alwaysDiscardsLateVideoFrames = YES;
if ([_session canAddOutput:_videoOutput]) {
    [_session addOutput:_videoOutput];  // 添加到Session
}
 
// 保存Connection,用於在SampleBufferDelegate中判斷數據來源(是Video/Audio?)
_videoConnection = [_videoOutput connectionWithMediaType:AVMediaTypeVideo];

實現 AVCaptureOutputDelegate:

- (void) captureOutput:(AVCaptureOutput *)captureOutput 
 didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer 
        fromConnection:(AVCaptureConnection *)connection
{
    // 這里的sampleBuffer就是采集到的數據了,但它是Video還是Audio的數據,得根據connection來判斷
    if (connection == _videoConnection) {  // Video
        /*
        // 取得當前視頻尺寸信息
        CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
        int width = CVPixelBufferGetWidth(pixelBuffer);
        int height = CVPixelBufferGetHeight(pixelBuffer);
        NSLog(@"video width: %d  height: %d", width, height);
        */
         NSLog(@"在這里獲得video sampleBuffer,做進一步處理(編碼H.264)");
    } else if (connection == _audioConnection) {  // Audio
        NSLog(@"這里獲得audio sampleBuffer,做進一步處理(編碼AAC)");
    }
}

關於實時編碼H.264和AAC Buffer,這里又是兩個技術點,之后再講吧。

配置完成,現在啟動 Session:

// 啟動 Session
[_session startRunning];

1.1 附加任務:將當前硬件采集視頻圖像顯示到屏幕

很簡單,發送端直接使用自家的AVCaptureVideoPreviewLayer顯示,so easy

_previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
_previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; // 設置預覽時的視頻縮放方式
[[_previewLayer connection] setVideoOrientation:AVCaptureVideoOrientationPortrait]; // 設置視頻的朝向
 
_previewLayer.frame = self.view.layer.bounds;
[self.view.layer addSublayer:_previewLayer];

然后將這個layer添加到界面中即可顯示了。

采集時候有個小坑,就是采集的圖像尺寸和方向設置。有空我會單開個帖子來聊聊。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM