8

嗨,我正在处理视频,我想从库中获取视频文件列表以显示并在我的应用程序中播放视频。谁能帮我。

4

7 回答 7

11
allVideos = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];

[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
 {
     if (group)
     {
         [group setAssetsFilter:[ALAssetsFilter allVideos]];
         [group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
          {
              if (asset)
              {
                  dic = [[NSMutableDictionary alloc] init];
                  ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
                  NSString *uti = [defaultRepresentation UTI];
                  NSURL  *videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
                  NSString *title = [NSString stringWithFormat:@"video %d", arc4random()%100];
                  UIImage *image = [self imageFromVideoURL:videoURL];
                  [dic setValue:image forKey:@"image"];
                  [dic setValue:title forKey:@"name"];
                  [dic setValue:videoURL forKey:@"url"];
                  [allVideos addObject:dic];
              }
          }];
     else
     {
     }
 }
  failureBlock:^(NSError *error)
 {
     NSLog(@"error enumerating AssetLibrary groups %@\n", error);
 }];
于 2013-07-15T12:45:12.213 回答
3

它将打开照片库并仅显示电影类型的内容。

#import <MobileCoreServices/MobileCoreServices.h>

UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentModalViewController:imagePicker animated:YES];
于 2013-07-11T06:00:24.283 回答
3

获取所有视频和缩略图的列表

感谢@Nikhil,他在这里分享了信息,它帮助了我,但仍然需要几个小时才能使代码可执行,因为他在回答中遗漏了一些东西

在此处输入图像描述

所以我想分享我的完整工作代码

1.只需添加框架AssetsLibraryAVFoundationMediaPlayer

2. AssetBrowserItem.hAssetBrowserItem.m 这里

3.使用下面的代码从ios设备库中获取所有视频的列表

4.运行应用程序并查看日志以获取视频详细信息

#import "HomeViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import "AssetBrowserItem.h"


@interface HomeViewController ()

@property (nonatomic, strong) ALAssetsLibrary *assetsLibrary;
@property (nonatomic, strong) NSURL *videoURL;
@property (nonatomic, strong) MPMoviePlayerController *mpVideoPlayer;
@property (nonatomic, strong) NSMutableArray *videoURLArray;
@property (nonatomic, strong) NSMutableArray *assetItems;
@property (nonatomic, strong) NSMutableDictionary *dic;

@end

@implementation HomeViewController

@synthesize assetsLibrary, assetItems,dic;
@synthesize videoURL,videoURLArray, mpVideoPlayer;

- (void)viewDidLoad
{
    [super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


#pragma mark - Show Video List Methods

- (IBAction)showVideoList:(id)sender
{
    [self buildAssetsLibrary];
}

- (void)buildAssetsLibrary
{
    assetsLibrary = [[ALAssetsLibrary alloc] init];
    ALAssetsLibrary *notificationSender = nil;

    videoURLArray = [[NSMutableArray alloc] init];

    NSString *minimumSystemVersion = @"4.1";
    NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
    if ([systemVersion compare:minimumSystemVersion options:NSNumericSearch] != NSOrderedAscending)
        notificationSender = assetsLibrary;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(assetsLibraryDidChange:) name:ALAssetsLibraryChangedNotification object:notificationSender];
    [self updateAssetsLibrary];
}

- (void)assetsLibraryDidChange:(NSNotification*)changeNotification
{
    [self updateAssetsLibrary];
}

- (void)updateAssetsLibrary
{
    assetItems = [NSMutableArray arrayWithCapacity:0];
    ALAssetsLibrary *assetLibrary = assetsLibrary;

    [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
    {
        if (group)
        {
            [group setAssetsFilter:[ALAssetsFilter allVideos]];
            [group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
             {
                 if (asset)
                 {
                     dic = [[NSMutableDictionary alloc] init];
                     ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
                     NSString *uti = [defaultRepresentation UTI];
                     videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];

                     mpVideoPlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];

                     NSString *title = [NSString stringWithFormat:@"%@ %lu", NSLocalizedString(@"Video", nil), [assetItems count]+1];

                     [self performSelector:@selector(imageFromVideoURL)];
                     [dic setValue:title forKey:@"VideoTitle"];//kName
                     [dic setValue:videoURL forKey:@"VideoUrl"];//kURL

                     AssetBrowserItem *item = [[AssetBrowserItem alloc] initWithURL:videoURL title:title];
                     [assetItems addObject:item];
                     [videoURLArray addObject:dic];

                     NSLog(@"Video has info:%@",videoURLArray);
                 }
                 NSLog(@"Values of dictonary==>%@", dic);

                 //NSLog(@"assetItems:%@",assetItems);
                 NSLog(@"Videos Are:%@",videoURLArray);
             } ];
        }
        // group == nil signals we are done iterating.
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                //[self updateBrowserItemsAndSignalDelegate:assetItems];
//                loadImgView.hidden = NO;
//                [spinner stopAnimating];
//                [loadImgView removeFromSuperview];
                //selectVideoBtn .userInteractionEnabled = YES;
            });
        }
    }
                              failureBlock:^(NSError *error)
    {
        NSLog(@"error enumerating AssetLibrary groups %@\n", error);
    }];
}

- (UIImage *)imageFromVideoURL
{

    UIImage *image = nil;
    AVAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];;
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    imageGenerator.appliesPreferredTrackTransform = YES;

    // calc midpoint time of video
    Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
    CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);

    // get the image from
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];

    if (halfWayImage != NULL)
    {
        // cgimage to uiimage
        image = [[UIImage alloc] initWithCGImage:halfWayImage];
        [dic setValue:image forKey:@"ImageThumbnail"];//kImage
        NSLog(@"Values of dictonary==>%@", dic);
        NSLog(@"Videos Are:%@",videoURLArray);
        CGImageRelease(halfWayImage);
    }
    return image;
}

@end
于 2015-02-05T12:06:30.070 回答
3

swift 4.0中,这就是我使用照片框架中的 fetchAsset() 方法从照片库中获取所有视频的方式。

您还可以使用谓词从特定文件夹中获取视频。

   func fetchAllVideos()
{
    //let albumName = "blah"
    let fetchOptions = PHFetchOptions()
    //        fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
    //uncomment this if you want video from custom folder
    fetchOptions.predicate = NSPredicate(format: "mediaType = %d ", PHAssetMediaType.video.rawValue )

    let allVideo = PHAsset.fetchAssets(with: .video, options: fetchOptions)
    allVideo.enumerateObjects { (asset, index, bool) in
        // videoAssets.append(asset)
        let imageManager = PHCachingImageManager()
        imageManager.requestAVAsset(forVideo: asset, options: nil, resultHandler: { (asset, audioMix, info) in
            if asset != nil {
                let avasset = asset as! AVURLAsset
                let urlVideo = avasset.url
                print(urlVideo)

            }
        })

    }

}
于 2019-11-22T14:13:19.530 回答
1

查看博客文章以使用照片框架获取所有视频资产 http://iavinashkashyap.blogspot.in/2016/11/get-list-of-all-videos.html

代码:

-(无效)getAllVideoAssets{

NSMutableArray *assets = [[NSMutableArray alloc] init];
//Fetch all video assets from Photos
PHFetchResult *assetResults = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:nil];
//get all assets
for (PHAsset *asset in assetResults){
    NSLog(@"asset type = %zd", asset.mediaType);
    [assets addObject:asset];
}
self.allVideoslistArray = [[NSMutableArray alloc] init];
//create an instance of PHImageManager
PHImageManager *manager = [PHImageManager defaultManager];
for(PHAsset *asset in assets){
    //block of code for represent video assets
    [manager requestAVAssetForVideo:asset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        if ([asset isKindOfClass:[AVURLAsset class]]) {
            NSURL *url = (NSURL *)[[(AVURLAsset *)asset URL] fileReferenceURL];
            UIImage *thumbnail = [self createThunbnailImage:url];
            [self.allVideoslistArray addObject:@{@"VideoUrl":url,@"ThumbnailImage":thumbnail, @"VideoAsset":asset}];
        }
    }];
}//end for loop

}

于 2016-11-28T09:06:26.800 回答
0

请参考以下链接。可能对你有帮助

http://www.raywenderlich.com/13418/how-to-play-record-edit-videos-in-ios
祝你好运!!!

于 2013-07-11T06:02:42.830 回答
0

使用此方法从库中选择视频。

      //Call this method.
     [self startMediaBrowserFromViewController: self usingDelegate: self];


   - (BOOL) startMediaBrowserFromViewController: (UIViewController*) controller usingDelegate: (id <UIImagePickerControllerDelegate, UINavigationControllerDelegate>) delegate{

       if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO) || (delegate == nil) || (controller == nil))
           return NO;

       UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
       mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;

       mediaUI.mediaTypes = [[[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil] autorelease];
       mediaUI.allowsEditing = YES;
       mediaUI.delegate = self;
       mediaUI.videoMaximumDuration = 60.0;
       //mediaUI.videoQuality = UIImagePickerControllerQualityTypeLow;

       [controller presentModalViewController: mediaUI animated: YES];
       return YES;
   }
于 2013-07-11T06:13:31.640 回答