Как получить экранное действие к файлу ролика с помощью Основы AV на Льве Mac OS X
Q: Как я получаю экранное действие к фильму Quicktime на Льве Mac OS X?
A: Начиная со Льва Mac OS X способ сделать фильм из экранного действия состоит в том, чтобы использовать Основу AV.
// Create an image from the entire main display
CGImageRef image = CGDisplayCreateImage(kCGDirectMainDisplay);
Посмотрите, Как взять снимок изображения экрана на Льве Mac OS X для получения дополнительной информации.
Чтобы выполнить снимок экрана в реальном времени и сохранить его к файлу ролика Quicktime, Вам нужны минимально три объекта AV:
AVCaptureSessionобъект, координирующий поток данных от входных источников AV до выводов.AVCaptureScreenInputобъект, который является входным источником данных, обеспечивающим видеоданные от данного дисплея.AVCaptureMovieFileOutputобъект, который является выходным местом назначения для Вас для записи полученных данных носителей в файл фильма в формате QuickTime.
В следующем примере код создает сеанс получения, добавляет экранный ввод для обеспечения видеокадров, добавляет выходное место назначения для сохранения полученных кадров, запускает поток данных от ввода до вывода и останавливает поток через 5 секунд. Позволяя классу соответствовать AVCaptureFileOutputRecordingDelegate протокол и установка записи делегируют должным образом, можно контролировать, когда запись закончена через метод делегата.
Перечисление 1 , соответствующее AVCaptureFileOutputRecordingDelegate протокол
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface Recorder : NSObject <AVCaptureFileOutputRecordingDelegate> {
@private
AVCaptureSession *mSession;
AVCaptureMovieFileOutput *mMovieFileOutput;
NSTimer *mTimer;
}
-(void)screenRecording:(NSURL *)destPath;
@end |
Экранный пример записи перечисления 2
-(void)screenRecording:(NSURL *)destPath
{
// Create a capture session
mSession = [[AVCaptureSession alloc] init];
// Set the session preset as you wish
mSession.sessionPreset = AVCaptureSessionPresetMedium;
// If you're on a multi-display system and you want to capture a secondary display,
// you can call CGGetActiveDisplayList() to get the list of all active displays.
// For this example, we just specify the main display.
CGDirectDisplayID displayId = kCGDirectMainDisplay;
// Create a ScreenInput with the display and add it to the session
AVCaptureScreenInput *input = [[[AVCaptureScreenInput alloc] initWithDisplayID:displayId] autorelease];
if (!input) {
[mSession release];
mSession = nil;
return;
}
if ([mSession canAddInput:input])
[mSession addInput:input];
// Create a MovieFileOutput and add it to the session
mMovieFileOutput = [[[AVCaptureMovieFileOutput alloc] init] autorelease];
if ([mSession canAddOutput:mMovieFileOutput])
[mSession addOutput:mMovieFileOutput];
// Start running the session
[mSession startRunning];
// Delete any existing movie file first
if ([[NSFileManager defaultManager] fileExistsAtPath:[destPath path]])
{
NSError *err;
if (![[NSFileManager defaultManager] removeItemAtPath:[destPath path] error:&err])
{
NSLog(@"Error deleting existing movie %@",[err localizedDescription]);
}
}
// Start recording to the destination movie file
// The destination path is assumed to end with ".mov", for example, @"/users/master/desktop/capture.mov"
// Set the recording delegate to self
[mMovieFileOutput startRecordingToOutputFileURL:destPath recordingDelegate:self];
// Fire a timer in 5 seconds
mTimer = [[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(finishRecord:) userInfo:nil repeats:NO] retain];
}
-(void)finishRecord:(NSTimer *)timer
{
// Stop recording to the destination movie file
[mMovieFileOutput stopRecording];
[mTimer release];
mTimer = nil;
}
// AVCaptureFileOutputRecordingDelegate methods
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
NSLog(@"Did finish recording to %@ due to error %@", [outputFileURL description], [error description]);
// Stop running the session
[mSession stopRunning];
// Release the session
[mSession release];
mSession = nil;
} |
История версии документа
| Дата | Примечания |
|---|---|
| 10.08.2011 | Исправленный ссылка. |
| 13.05.2011 | Новый документ, показывающий, как получить экранное действие к файлу ролика с помощью Основы AV на Льве Mac OS X. |