How to get thumbnail of the captured video and show in UIImageView - iphone

I am capturing video it works fine but i want to get thumbnail of that video and show it in ImageView any idea how to get this below is my code.
if ([type isEqualToString:(NSString *)kUTTypeVideo] || [type isEqualToString:(NSString *)kUTTypeMovie])
{
NSURL*videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"found a video");
videoData = [[NSData dataWithContentsOfURL:videoURL] retain];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"dd-MM-yyyy_HH:mm:SS"];
NSDate *now = [[[NSDate alloc] init] autorelease];
NSDate* theDate = [dateFormat stringFromDate:now];
NSString*myDate=[dateFormat stringFromDate:theDate];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Default Album"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
NSString*test=#"test";
NSString*testUser=[test stringByReplacingOccurrencesOfString:#" " withString:#""];
videopath= [[[NSString alloc] initWithString:[NSString stringWithFormat:#"%#/%#.mov",documentsDirectory,testUser]] autorelease];
BOOL success = [videoData writeToFile:videopath atomically:NO];
NSLog(#"Successs:::: %#", success ? #"YES" : #"NO");
NSLog(#"video path --> %#",videopath);
NSURL *movieURL = [NSURL fileURLWithPath:videopath];
AVURLAsset *avUrl = [AVURLAsset assetWithURL:movieURL];
CMTime time = [avUrl duration];
int seconds = ceil(time.value/time.timescale);
// durationTime=[NSString stringWithFormat:#"%d",seconds];
// insertTime=[NSString stringWithFormat:#"%d",seconds];
NSString*messageA=[NSString stringWithFormat:#"You have recorded video of duration of %d seconds ",seconds];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:messageA
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:MM:SS"];
//[formatter setDateFormat:#"MM-dd-yyyy"];
NSString* str = [formatter stringFromDate:date];

Try this one:
#import<AssetsLibrary/AssetsLibrary.h>
#import<AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import <CoreMedia/CoreMedia.h>
#import <MediaPlayer/MediaPlayer.h>
//create thumbnail from video
AVAsset *asset = [AVAsset assetWithURL:url];// url= give your url video here
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
CMTime time = CMTimeMake(1, 5);//it will create the thumbnail after the 5 sec of video
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
cell.backGround.image=thumbnail;// whichever imageview you want give this image
it will help you.

add that MPMoviePlayerController (see below) is a much faster option. The code above takes a good 5-10 seconds to generate a thumbnail, and also you can show in UIImageview
NSURL *videoURL = [NSURL fileURLWithPath:url];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
//Player autoplays audio on init
[player stop];
[player release];

#import <AVFoundation/AVFoundation.h>
-(UIImage *)generateThumbImage : (NSString *)filepath {
NSURL *url = [NSURL fileURLWithPath:filepath];
AVAsset *asset = [AVAsset assetWithURL:url];
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
CMTime time = [asset duration];
time.value = 1000; //Time in milliseconds
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef); // CGImageRef won't be released by ARC
return thumbnail;
}

Related

How to get file size of file from iPhone documents folder

I have in which i save video file in documents folder it works fine,but i want to get the file size of the saved file,I have searched but did not get result using NSfileManager,here is the code which i use for saving video.I want to get the file size and show it on UILabel.
thanks
NSURL*videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"found a video");
videoData = [[NSData dataWithContentsOfURL:videoURL] retain];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"dd-MM-yyyy_HH:mm:SS"];
NSDate *now = [[[NSDate alloc] init] autorelease];
NSDate* theDate = [dateFormat stringFromDate:now];
NSString*myDate=[dateFormat stringFromDate:theDate];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Default Album"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
NSString*test=#"test";
NSString*testUser=[test stringByReplacingOccurrencesOfString:#" " withString:#""];
videopath= [[[NSString alloc] initWithString:[NSString stringWithFormat:#"%#/%#.mp4",documentsDirectory,testUser]] autorelease];
BOOL success = [videoData writeToFile:videopath atomically:NO];
NSLog(#"Successs:::: %#", success ? #"YES" : #"NO");
NSLog(#"video path --> %#",videopath);
NSURL *movieURL = [NSURL fileURLWithPath:videopath];
AVURLAsset *avUrl = [AVURLAsset assetWithURL:movieURL];
CMTime time1 = [avUrl duration];
int seconds = ceil(time1.value/time1.timescale);
// durationTime=[NSString stringWithFormat:#"%d",seconds];
// insertTime=[NSString stringWithFormat:#"%d",seconds];
NSString*messageA=[NSString stringWithFormat:#"You have recorded video of duration of %d seconds ",seconds];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:messageA
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
AVAsset *asset = [AVAsset assetWithURL:movieURL];// url= give your url video here
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
CMTime time = CMTimeMake(1, 5);//it will create the thumbnail after the 5 sec of video
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
thumbnailImageView.image=thumbnail;
Note: Above Method is deprecated so, use below method
Objective-C:
NSError* error;
NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath:mediaURL error: &error];
NSNumber *size = [fileDictionary objectForKey:NSFileSize];
Swift:
do
{
let fileDictionary = try FileManager.default.attributesOfItem(atPath: urlString)
let fileSize = fileDictionary[FileAttributeKey.size]
print ("\(fileSize)")
}
catch{}
** this file size in bytes
Try this its help you
NSDictionary *fileDictionary = [[NSFileManager defaultManager] fileAttributesAtPath:videopath traverseLink:YES];
fileSize = [fileDictionary fileSize];
Use NSFileManager attributesOfItemAtPath:error
https://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/attributesOfItemAtPath:error:
It returns an NSDictionary of file attributes and one key it contains is NSFileSize, the size of the file.
try this way.
// Get file size
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [documentsDirectory stringByAppendingString:[directoryContent objectAtIndex:indexPath.row]];
NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:filePath traverseLink:YES];
if(fileAttributes != nil)
{
NSString *fileSize = [fileAttributes objectForKey:NSFileSize];
[[cell detailTextLabel] setText:[NSString stringWithFormat:#"%# kb", fileSize]];
NSLog(#"File size: %# kb", fileSize);
}
Before few days I was also searching for something very similar. I was needed to upload the local file to the dropbox and here is something that worked for me: Check the below link:
https://stackoverflow.com/a/1694928/2098401

I want to display a videothumbnail image of a video from url in my uiimageview for iphone

Is it possible to get the first image frame of a video and display it in uiimageview . My video is saved in the server. i need to call the url to play the video
An example:
NSURL *videoURl = [NSURL fileURLWithPath:videoPath];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURl options:nil];
AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generate.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 60);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *img = [[UIImage alloc] initWithCGImage:imgRef];
[YourImageView setImage:img];
Hope it helps..
I use this method to do the same
/**
* This method retunrs a thumbnail of a Video file
*/
+ (UIImage *)generateThumbnailIconForVideoFileWith:(NSURL *)contentURL WithSize:(CGSize)size
{
UIImage *theImage = nil;
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:contentURL options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.maximumSize=size;
generator.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(100,100); //change whatever you want here.
CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:&err];
theImage = [[UIImage alloc] initWithCGImage:imgRef] ;
CGImageRelease(imgRef);
return theImage;
}
You can do this using MPMoviePlayerController like bellow..
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:yourVideoURL];
UIImage *videoThumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
[player stop];
Also see another answer with AVURLAsset from this link getting-thumbnail-from-a-video-url-or-data-in-iphone-sdk

NOt able to convert from MPMediaItem(mp3 song) to NSData

I have tried following code :
These is my delegate method of MPMediPickerController :
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection {
// Dismiss the media item picker.
[self dismissModalViewControllerAnimated: YES];
NSLog(#"%# %d",mediaItemCollection,mediaItemCollection.count);
NSArray *newMediaItem= [mediaItemCollection items];
MPMediaItem *item=[[newMediaItem objectAtIndex:0] retain];
[self uploadMusicFile:item];
}
This is my custom method MPMediaItem to NSData:
- (void) uploadMusicFile:(MPMediaItem *)song
{
NSURL *url = [song valueForProperty: MPMediaItemPropertyAssetURL];
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL: url options:nil];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset
presetName: AVAssetExportPresetPassthrough];
exporter.outputFileType = #"public.mpeg-4";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *exportFile = [documentsDirectory stringByAppendingPathComponent:
#"exported.mp4"];
NSURL *exportURL = [[NSURL fileURLWithPath:exportFile] retain];
exporter.outputURL = exportURL;
[exporter exportAsynchronouslyWithCompletionHandler:
^{
NSData *data = [NSData dataWithContentsOfFile: [documentsDirectory
stringByAppendingPathComponent: #"exported.mp4"]];
NSLog(#"%#",data);
}];
}
I am getting "null" in NSlog.
I have also check this post :
how to convert nsdata to MPMediaitem song iOS Sdk
but not getting solution.
I am using xcode 4.6 and ios 6.1.
Can any one tell me what is wrong here?

Attach sound file from gallery in iOS

Is it possible to access sound files gallery just like image gallery in my iOS app, I have tried searching on net but have not found any good content about it.
You can refer to the AddMusic sample application from Apple to see how its done...
Yes you can upload it to server. Use below code :
When you select a song from picker
- (void)mediaPicker: (MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
MPMediaItem *song = nil ;
[self dismissModalViewControllerAnimated:YES];
if ([mediaItemCollection count] < 1)
{
return;
}
[song release];
song = [[[mediaItemCollection items] objectAtIndex:0] retain];
//song.accessibilityHin
[self uploadMusicFile:song];
}
- (void) uploadMusicFile:(MPMediaItem *)song
{
// Init audio with playback capability
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
NSURL *assetURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
// to get uniqe time interval
[[NSDate date] timeIntervalSince1970];
// convert this ti string
NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970];
NSString *intervalSeconds = [NSString stringWithFormat:#"%0.0f",seconds];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset presetName: AVAssetExportPresetPassthrough];
exporter.outputFileType = #"public.mpeg-4";
NSString *exportFile = [[NSString alloc] initWithString:[DOCUMENTS_FOLDER stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mp4",intervalSeconds]]];
NSURL *exportURL = [[NSURL fileURLWithPath:exportFile] retain];
exporter.outputURL = exportURL;
[exporter exportAsynchronouslyWithCompletionHandler:
^{
NSData *data = [NSData dataWithContentsOfURL:exportURL];
// Here your upload code
}];
}

ID3 Artwork Tags from MP3 In Documents Directory iPhone Development

I have several MP3 files in the user's documents directory, and I want to be able to get and display the ID3 Artwork Tags. I have tried using NSURLAsset, but I am unsure how to convert that to a UIImage or a UIImageView!
Thanks!
You have to use the AVAsset class:
For instance:
NSString *mp3Path = [[NSBundle mainBundle] pathForResource:#"audio-file" ofType:#"mp3"];
NSURL *url = [NSURL fileURLWithPath:mp3Path];
AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
for (NSString *format in [asset availableMetadataFormats]) {
for (AVMetadataItem *item in [asset metadataForFormat:format]) {
if ([[item commonKey] isEqualToString:#"artwork"]) {
NSData *data = [(NSDictionary *)[item value] objectForKey:#"data"];
UIImageView *img = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
[self.view addSubview:img];
continue;
}
NSLog(#"%#", item);
}
}
NSLog(#"> Duration = %.2f seconds", CMTimeGetSeconds(asset.duration));