How can i play video (By Name) from document directory ? - iphone

In my application i store my video in document directory with name is 'video2.MOV' and i want to play it.
Here problem is that i am not able to get this video (name is 'video2.MOV') from document directory.
My Code :
-(void)playVideo:(NSTimer *)theTimer
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"video2.MOV"];
NSLog(#"filePath - %#",filePath);
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"contentPath - %#",content);
MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:content]];
[[CCDirector sharedDirector] presentMoviePlayerViewControllerAnimated:videoPlayerView];
[videoPlayerView.moviePlayer play];
}
In console, each time i got contentPath is NULL, so may be i am not able to play video.
Here, What is my mistake. please give me suggestion on this issue.

Try this:
- (NSString*)GetDocumentFilePath:(NSString*)filename
{
NSLog(#"%#",filename);
// NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString* file = [[NSString alloc]initWithFormat:#"%#",filename];
NSString* path = [documentsDirectory stringByAppendingPathComponent:file];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
//NSString *bundle = [[NSBundle mainBundle] pathForResource:filename ofType:#"plist"]; //5
//[fileManager copyItemAtPath:bundle toPath:path error:&error]; //6
}
return path;
}
and get file path like this:
NSURL *URL = [NSURL fileURLWithPath:[self GetDoucmentPath:path]];
MPMoviePlayerController* theMovie=[[MPMoviePlayerController alloc] initWithContentURL:pptURL];
theMovie.scalingMode=MPMovieScalingModeAspectFill;
theMovie.view.frame = CGRectMake(60, 20, 700, 500);
theMovie.view.center = self.view.center;
//[self.view addSubview:theMovie.view];
// Register for the playback finished notification.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(onStop)
name:MPMoviePlayerPlaybackDidFinishNotification
object:theMovie];
// Movie playback is asynchronous, so this method returns immediately.
[self.view addSubview:theMovie.view];
[theMovie play];
Hope it Helps!!

Instead of using content use filePath instead to get to the movie file:
MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:filePath]];

Related

How to get thumbnails of a video saved in document directory

I saved the captured video in document directory as shown below and now I want to display the thumbnails and play the same video.How to do this ?
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info
{
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:NO];
// Handle a movie capture
if (CFStringCompare ((__bridge_retained CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo)
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *movieName = [NSString stringWithFormat:#"%#.mov",[CoreDataFunctions getNameForVideoForDate:[CalendarFunctions getCurrentDateString]]];
NSString *moviePath = [documentsDir stringByAppendingPathComponent:movieName];
NSURL * movieURL = [info valueForKey:UIImagePickerControllerMediaURL];
NSData * movieData = [NSData dataWithContentsOfURL:movieURL];
NSLog(#"%#",moviePath);
if([movieData writeToFile:moviePath atomically:NO])
{
if(![CoreDataFunctions saveVideoInfoInDatabaseForDate:[CalendarFunctions getCurrentDateString]])
{
NSLog(#"Video was saved in doucment directory but could not be saved in core data");
}
}
else
{
NSLog(#"Video could not be saved to the document directry");
}
}
}
Get videos from doc dir like this
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError * error;
NSArray *directoryContents = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:documentsDirectory error:&error];
//Take all images in NSMutableArray
NSMutableArray *arrVideoImages = [[NSMutableArray alloc]init];
for(NSString *strFile in directoryContents)
{
NSString *strVideoPath = [NSString stringWithFormat:#"%#/%#",documentsDirectory,strFile];
UIImage *img = [self getThumbNail:strVideoPath];
[arrVideoImages addObject:img];
}
Also add this method:
-(UIImage *)getThumbNail:(NSString)stringPath
{
NSURL *videoURL = [NSURL fileURLWithPath:stringPath];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
//Player autoplays audio on init
[player stop];
[player release];
return thumbnail;
}

Sharing multiple files on App Via iTunes File Sharing (Code shows 1 file)

I'm trying to file share multiple files with iTunes file share.
Here is the current code.
Delegate.h
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// file sharing trying
{
NSString *fileName = #"Test.mp3";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentDBFolderPath = [documentsDirectory stringByAppendingPathComponent:fileName];
if (![fileManager fileExistsAtPath:documentDBFolderPath])
{
NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
[fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error];
}
}
[self.window makeKeyAndVisible];
return YES;
}
At the moment only 1 file gets shared.
Thanks
I assume you want to add a bunch of files in an NSArray? then loop through it like this:
NSArray *names = [NSArray arrayWithObjects: #"foo", #"bar", nil];
for (NSString *fileName in names)
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentDBFolderPath = [documentsDirectory stringByAppendingPathComponent:fileName];
if (![fileManager fileExistsAtPath:documentDBFolderPath])
{
NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
[fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error];
}
}

UIWebView displays locally stored document on simulator but not device

I have an issue where I'm trying to view a document (Word document, image, or video) that I have stored locally. I'm using UIWebView and on the Simulator it works perfectly, but on the device, it's a blank screen (no errors thrown in console). Here's my code to view the document:
UIWebView *newWebView;
if (appDelegate.IS_IPAD)
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
}
else
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
}
newWebView.scalesPageToFit = YES;
[self setWebView: newWebView];
[newWebView release], newWebView = nil;
[[self webView] setDelegate: self];
[[self view] addSubview:[self webView]];
NSURL *nsURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
[[self webView] loadRequest:[NSURLRequest requestWithURL:nsURL]];
Here's how I'm saving the document locally before viewing. I do think the file is getting successfully saved on the device as it does on the simulator.
// Save the file on the device
NSURL *contentUrl = [NSURL URLWithString:selectedContent.contentUrl];
NSString *fileName = [[contentUrl absoluteString] lastPathComponent];
NSString *homeDirectoryPath = NSHomeDirectory(); // Create the path
NSString *unexpandedPath = [homeDirectoryPath stringByAppendingString:#"/MyApp/"];
NSString *folderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];
NSString *unexpandedImagePath = [folderPath stringByAppendingFormat:#"/%#", fileName];
NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL])
{
[[NSFileManager defaultManager] createDirectoryAtPath:nil withIntermediateDirectories:NO attributes:nil error:nil];
}
// Do the actual write of the file to the device
NSData *fileData = [NSData dataWithContentsOfURL:myUrl]; // Create the file data reference
[fileData writeToFile:filePath atomically:YES]; //Save the document to the home directory
Watch out for case issues. The simulator is not case sensitive whereas the iPhone is!
I solved this by saving my document to the default Documents Directory. Here's the code I used to accomplish this:
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [arrayPaths objectAtIndex:0];
NSString *filePath = [docDirectory stringByAppendingString:#"/"];
filePath = [filePath stringByAppendingString:fileName];
NSData *fileData = [NSData dataWithContentsOfURL:myUrl];
[fileData writeToFile:filePath atomically:YES];

how to stream a video in iphone

does initWithContentURL: in MPMoviePlayerController download the video file at first and then start playing or will it stream file like in youtube?
I want to play an video located in server through streaming in order not to waste of time.
How to perform streaming in iphone?
Can anyone please suggest me if u know.
Thanks in advance.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
NSString *appFile;
NSArray *myWords = [[NSString stringWithFormat:#"%#",[[videolistArray objectAtIndex:[number intValue]] valueForKey:#"video"]] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"/"]];
appFile = [documentsDirectory stringByAppendingPathComponent:[myWords lastObject]];
NSFileManager *fileMgr=[NSFileManager defaultManager];
if (![fileMgr fileExistsAtPath:appFile]) {
NSData *imageData;
NSURL *imageURL = [[[NSURL alloc] initWithString:[[videolistArray objectAtIndex:[number intValue]] valueForKey:#"video"] ] autorelease];
if (imageURL) {
imageData = [NSData dataWithContentsOfURL:imageURL];
}
[imageData writeToFile:appFile atomically:YES];
}
[pool release];
if (spinner) {
[spinner stopAnimating];
[spinner removeFromSuperview];
[spinner release];
spinner = nil;
}
---------------------------Above methode is for save video in file system of iphone
-------------------- Below method to play that movie continuos
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
NSArray *myWords = [videoString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"/"]];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:[myWords lastObject]];
NSLog(#"%#",[myWords lastObject]);
NSURL *url = [NSURL fileURLWithPath:appFile];
self.videoMPPlayer =[[MPMoviePlayerController alloc] initWithContentURL:url];
self.videoMPPlayer.view.frame = CGRectMake(0, 0, 320, 480);
self.videoMPPlayer.scalingMode = MPMovieScalingModeAspectFill;
self.videoMPPlayer.controlStyle = MPMovieControlStyleNone;
// Register for the playback finished notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(movieLoadStateChanges:) name:MPMoviePlayerLoadStateDidChangeNotification object:videoMPPlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(myMovieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:videoMPPlayer];
// Movie playback is asynchronous, so this method returns immediately.
[self.videoMPPlayer play];

iphone calls both if and else at the same time?

I need to determine what file type a file is and then perform a certain action for it. this seems to work fine for some types, however all media types such as videos and sound files get mixed up. I determine the file type by doing this:
BOOL matchedMP3 = ([[rowValue pathExtension] isEqualToString:#"mp3"]);
if (matchedMP3 == YES)
{
NSLog(#"Matched MP3");
}
I do this for various file types and just define an "else" for all the others. Here's the problem though. The iPhone calls them both. Here's what the log reveals:
2010-05-11 18:51:12.421 Test [5113:207] Matched MP3
2010-05-11 18:51:12.449 Test [5113:207] Matched ELSE
I've never seen anything like this before.
This is my "matchedMP3" function:
BOOL matchedMP3 = ([[rowValue pathExtension] isEqualToString:#"mp3"]);
if (matchedMP3 == YES)
{
NSLog(#"Matched MP3");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
self.directoryContent = [manager directoryContentsAtPath:documentsDirectory];
NSString *errorMessage = [documentsDirectory stringByAppendingString:#"/"];
NSString *urlAddress = [errorMessage stringByAppendingString:rowValue];
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:urlAddress]];
moviePlayer.movieControlMode = MPMovieControlModeDefault;
moviePlayer.backgroundColor = [UIColor blackColor];
[moviePlayer play];
}
and here's the else statement:
else {
NSLog(#"Matched ELSE");
[[NSUserDefaults standardUserDefaults] setObject:rowValue forKey:#"rowValue"];
NSString*rowValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"rowValue"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
self.directoryContent = [manager directoryContentsAtPath:documentsDirectory];
NSString *errorMessage = [documentsDirectory stringByAppendingString:#"/"];
NSString *urlAddress = [errorMessage stringByAppendingString:rowValue];
webViewHeader.prompt = rowValue;
[documentViewer setDelegate:self];
NSString *encodedString = [urlAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//Create a URL object.
NSURL *url = [NSURL URLWithString:encodedString];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[documentViewer loadRequest:requestObj];
[navigationController pushViewController:webView animated:YES];
}
I can't see a reason why it wouldn't work. What happens is that both the webview and the MediaPlayer toggle their own player, so they overlap and play their sound/video a few secs apart from each other.
Any help would be appreciated & thank for you taking the time to read through my code.
Didn't you mistakenly do something like
if(conditionA)
{
...
}
if(conditionB)
{
...
}
else
{
....
}
In this case, if conditionA is satisfied but conditionB is not, the else clause is executed, because the first if clause finishes at the second if. You would want
if(conditionA)
{
...
}
else if(conditionB)
{
...
}
else
{
....
}
instead. Beware the else if.
By the way, you don't have to and shouldn't compare a BOOL against YES.
if(matchedMP3)
is enough. Remember, if accepts a boolean expression inside. A boolean value is a boolean expression!