13

私は、AVFoundation を使用して記録と保存を設定および処理する iOS 8 用のカメラ アプリを作成しています (ImagePickerController ではありません)。AVCaptureMovieFileOutput クラスの maxRecordedFileSize 属性を使用して、ユーザーが電話で利用可能なすべてのスペースを埋めることができるように保存しようとしています (Apple 用に残された 250MB のバッファを差し引いたもの)。

- (unsigned long long) availableFreespaceInMb {
unsigned long long freeSpace;
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];

if (dictionary) {
    NSNumber *fileSystemFreeSizeInBytes = [dictionary objectForKey: NSFileSystemFreeSize];
    freeSpace = [fileSystemFreeSizeInBytes unsignedLongLongValue];

} else {
    NSLog(@"Error getting free space");
    //Handle error
}

//convert to MB
freeSpace = (freeSpace/1024ll)/1024ll;
freeSpace -= _recordSpaceBufferInMb; // 250 MB
NSLog(@"Remaining space in MB: %llu", freeSpace);
NSLog(@"    Diff Since Last: %llu", (_prevRemSpaceMb - freeSpace));

_prevRemSpaceMb = freeSpace;
return freeSpace;

}

AVErrorMaximumFileSizeReached は、使用可能なスペース (マイナス バッファー) がゼロになるとスローされ、保存エラーはスローされませんが、ビデオはカメラ ロールに表示されず、保存されません。maxRecordedDuration フィールドを設定すると、 AVErrorMaximumDurationReached がスローされ、ビデオは保存されます。最大サイズから最大時間を計算しますが、フレーム圧縮のために常に十分なスペースが残っています。

- (void) toggleMovieRecording
{
double factor = 1.0;
if (_currentFramerate == _slowFPS) {
    factor = _slowMotionFactor;
}

double availableRecordTimeInSeconds = [self remainingRecordTimeInSeconds] / factor;
unsigned long long remainingSpace = [self availableFreespaceInMb] * 1024 * 1024;

if (![[self movieFileOutput] isRecording]) {
    if (availableSpaceInMb < 50) {
        NSLog(@"TMR:Not enough space, can't record");
        [AVViewController currentVideoOrientation];
        [_previewView memoryAlert];
        return;
    }
}

if (![self enableRecording]) {
    return;
}

[[self recordButton] setEnabled:NO];

dispatch_async([self sessionQueue], ^{
    if (![[self movieFileOutput] isRecording])
    {            
        if ([[UIDevice currentDevice] isMultitaskingSupported])
        {
            [self setBackgroundRecordingID:[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil]];
        }

        // Update the orientation on the movie file output video connection before starting recording.
        [[[self movieFileOutput] connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation: [AVViewController currentVideoOrientation]];//[[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] videoOrientation]];

        // Start recording to a temporary file.
        NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[@"movie" stringByAppendingPathExtension:@"mov"]];

        // Is there already a file like this?
        NSFileManager *fileManager = [NSFileManager defaultManager];

        if ([fileManager fileExistsAtPath:outputFilePath]) {
            NSLog(@"filexists");
            NSError *err;
            if ([fileManager removeItemAtPath:outputFilePath error:&err] == NO) {
                NSLog(@"Error, file exists at path");
            }
        } 

        [_previewView startRecording];

        // Set the movie file output to stop recording a bit before the phone is full
        [_movieFileOutput setMaxRecordedFileSize:remainingSpace]; // Less than the total remaining space
       // [_movieFileOutput setMaxRecordedDuration:CMTimeMake(availableRecordTimeInSeconds, 1.0)];

        [_movieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputFilePath] recordingDelegate:self];
    }
    else
    {
        [_previewView stopRecording];
        [[self movieFileOutput] stopRecording];
    }
});
}

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error

NSLog(@"AVViewController: didFinishRecordingToOutputFile");

if (error) {
    NSLog(@"%@", error);
    NSLog(@"Caught Error");
    if ([error code] == AVErrorDiskFull) {
        NSLog(@"Caught disk full error");
    } else if ([error code] == AVErrorMaximumFileSizeReached) {
        NSLog(@"Caught max file size error");
    } else if ([error code] == AVErrorMaximumDurationReached) {
        NSLog(@"Caught max duration error");
    } else {
        NSLog(@"Caught other error");
    }

    [self remainingRecordTimeInSeconds];

    dispatch_async(dispatch_get_main_queue(), ^{
        [_previewView stopRecording];
        [_previewView memoryAlert];
    });
}

// Note the backgroundRecordingID for use in the ALAssetsLibrary completion handler to end the background task associated with this recording. This allows a new recording to be started, associated with a new UIBackgroundTaskIdentifier, once the movie file output's -isRecording is back to NO — which happens sometime after this method returns.
UIBackgroundTaskIdentifier backgroundRecordingID = [self backgroundRecordingID];
[self setBackgroundRecordingID:UIBackgroundTaskInvalid];

[[[ALAssetsLibrary alloc] init] writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) {
    if (error) {
        NSLog(@"%@", error);
        NSLog(@"Error during write");
    } else {
        NSLog(@"Writing to photos album");
    }

    [[NSFileManager defaultManager] removeItemAtURL:outputFileURL error:nil];

    if (backgroundRecordingID != UIBackgroundTaskInvalid)
        [[UIApplication sharedApplication] endBackgroundTask:backgroundRecordingID];
}];

if (error) {
    [_session stopRunning];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), _sessionQueue, ^{
        [_session startRunning];
    });
}

両方のエラーがスローされると、「写真アルバムへの書き込み」が表示されます。私はこれに完全に困惑しています。iOSに関する洞察はありますか?

4

1 に答える 1

2

プロパティとメソッドが欠落しているため、提供したコード サンプルをテストするのは困難です。あなたのコードをコンパイルすることはできませんが、問題の原因となっている危険信号がいくつかあることは間違いありません。以下の問題は、次の内部で見つかりました。 captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:

問題 1: メソッドは渡されたエラーを処理していますが、メソッドの実行を続けています。代わりに、次のようにする必要があります。

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error { 
    if (error) {
        // handle error then bail
        return;
    }

    // continue on
}

問題 2: インスタンス化する ALAssetsLibrary オブジェクトはプロパティに格納されていないため、captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:終了するとオブジェクトが解放されます (完了ブロックが起動されない可能性があります)。代わりに、次のようにする必要があります。

// hold onto the assets library beyond this scope
self.assetsLibrary = [[ALAssetsLibrary alloc] init];

// get weak reference to self for later removal of the assets library
__weak typeof(self) weakSelf = self;
[self.assetsLibrary writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) {
    // handle error
    // handle cleanup

    // cleanup new property
    weakSelf.assetsLibrary = nil;
}];

これらの問題を修正しても問題が解決しない場合は、不足しているコードを提供してサンプルをコンパイルしてください。

于 2015-08-13T23:45:33.707 に答える