In my iPhone app, I am taking video using ImagePickerview and storing it to document directory
For iOS4 (device iPod) I can play video stored in document directory but for iOS 5 (device iPad) the same code is not working for playing video.
so for iOS 5 is there any different way for storing and playing video from document directory
(I also tried with library directory)
-(IBAction)saveVideo:(id)sender
{
imagepicker = [[UIImagePickerController alloc] init];
imagepicker.delegate=self;
if([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerSourceTypeCamera])
{
[imagepicker setSourceType:UIImagePickerControllerSourceTypeCamera];
[imagepicker setMediaTypes:[UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera]];
[imagepicker setCameraDevice:UIImagePickerControllerCameraCaptureModeVideo];
[self presentModalViewController:imagepicker animated:YES];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSMutableString *tempPath = [[[info valueForKey:#"UIImagePickerControllerMediaURL"] absoluteString] mutableCopy];
NSString *newPath1 = [NSString stringWithFormat:#"myVideo.mov"];
[tempPath replaceOccurrencesOfString:#"file://localhost/private/" withString:#"/" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempPath length])];
NSFileManager *manager = [NSFileManager defaultManager];
NSError *error = nil;
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], newPath1];
NSString *newPath = [NSString stringWithFormat:#"%#/%#", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], newPath1];
BOOL success = [manager copyItemAtPath:tempPath toPath:newPath error:&error];
if(error){
NSLog(#"New Path: %#", newPath);
NSLog(#"Error: %#", error);
}
if(success)
{
NSLog(#"Succeed");
}
[self dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
-(IBAction)playVideo:(id)sender
{
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:#"myVideo.mov"];
NSURL *url = [[NSURL alloc] initWithString:myDBnew];
NSLog(#"URL== %#",url);
moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:url];
// [[NSNotificationCenter defaultCenter] addObserver:self
// selector:#selector(moviePlayBackDidFinish:)
// name:MPMoviePlayerPlaybackDidFinishNotification
// object:moviePlayer];
moviePlayer.controlStyle = MPMovieControlStyleDefault;
moviePlayer.shouldAutoplay = YES;
[self.view addSubview:moviePlayer.view];
[moviePlayer setFullscreen:YES animated:YES];
}
What could be wrong?
Here is the code.
If I add the video file into my project and use below code it is playing Video The only thing is it is not playing video from document directory
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"myVideo" ofType:#"mov"]];
moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:url];
Even in iTunes via flittering I can see the file:"myVideo.mov", after running the app in device means This codes recording and storing video but not able to read or play.
Here in my code the problem was the way i am creating url
NSURL *url = [[NSURL alloc] initWithString:myDBnew];
which doesn't work for ios5 so i replaced in code by
NSURL *url = [[NSURL alloc] initFileURLWithPath:<#(NSString *)#> isDirectory:<#(BOOL)#>];
Related
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]];
I received the video file contents in the format of NSData and I am playing that file in MPMoviePlayerController successfully with following code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *FileExtension=[[NSString alloc]init];
if([contentType hasPrefix:#"video"] || [contentType isEqualToString:#"application/video"]) {
FileExtension=#"mov";
//FileExtension=#"mp4";
}
else
{
FileExtension=[contentType lastPathComponent];
}
//appFile is type of NSString.
appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"MyFile.%#",FileExtension]];
//videoData is type of NSData
[videoData writeToFile:appFile atomically:YES];
NSURL *fileURL = [NSURL fileURLWithPath:appFile isDirectory:NO];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
moviePlayerController.view.frame = self.view.bounds;
moviePlayerController.movieSourceType = MPMovieSourceTypeFile;
moviePlayerController.fullscreen = YES;
moviePlayerController.shouldAutoplay=NO;
[self.view addSubview:moviePlayerController.view];
[moviePlayerController prepareToPlay];
but I am unable to write/save this video file to camera roll,this is my code for writing code to the camera roll.
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSURL *filePathURL = [NSURL fileURLWithPath:appFile isDirectory:NO];
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:filePathURL]) {
[library writeVideoAtPathToSavedPhotosAlbum:filePathURL completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(#"Not success");
} else {
NSLog(#"success");
}
}];
}
this code is work fine when I set mimeType/file_format as .mov & .3Gp but I have problem related to save video to the camera roll when mimeType/file_format as .mp4 file.
You can convert your .mp4 to .mov if you change your appFile this way:
Your code:
appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"MyFile.%#",FileExtension]];
New code:
appFile = [documentsDirectory stringByAppendingPathComponent:#"MyFile.mov"];
The SO automatically converts .mp4 to .mov
I have been trying to play a mp4 file, I am receiving url from server, I have given that to MPMoviePlayerController, player is loading but file is not playing. Here is the code...
NSURL *url = [NSURL URLWithString:obj->msg_url]; // obj->url is a html php url not a direct file url.
moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:url];
moviePlayer.controlStyle = MPMovieControlStyleDefault;
moviePlayer.shouldAutoplay = YES;
[self.view addSubview:moviePlayer.view];
[moviePlayer setFullscreen:YES animated:YES];
So in this case how can I use MPMoviePlayerController to play from html url. Any idea?
thanks
Try
[moviePlayer play];
It seems shouldAutoplay does not always have the desired effect.
I have downloaded first and played its working now.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"sample.mp4"];
[urlData writeToFile:filePath atomically:YES];
NSURL *file_url = [NSURL fileURLWithPath:filePath];
moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:file_url];
moviePlayer.controlStyle = MPMovieControlStyleDefault;
moviePlayer.shouldAutoplay = YES;
[self.view addSubview:moviePlayer.view];
[moviePlayer setFullscreen:YES animated:YES];
I am working on app where i am attaching a Audio file from ipod library
i Get the audio detail using MPMediaPickerController. I get all the details. I even get the path and URl for the Audio. I even attach the audio in email and which is visible in compose view of the Email.
But when it is sent it is not visible.
Plz help me with the same.
-(void)displayComposerSheet {
NSMutableString *sub=[[NSMutableString alloc]init];
[sub setString:[NSString stringWithString:#"HiFive"]];
NSURL *assetURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
NSString *str=[song valueForProperty:MPMediaItemPropertyTitle];
str=[str stringByAppendingFormat:#".mp3"];
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
NSError *assetError = nil;
AVAssetReader *assetReader = [[AVAssetReader assetReaderWithAsset:songAsset
error:&assetError]retain];
if (assetError) {
NSLog (#"error: %#", assetError);
return;
}
AVAssetReaderOutput *assetReaderOutput = [[AVAssetReaderAudioMixOutput
assetReaderAudioMixOutputWithAudioTracks:songAsset.tracks
audioSettings: nil]
retain];
if (! [assetReader canAddOutput: assetReaderOutput]) {
NSLog (#"can't add reader output... die!");
return;
}
[assetReader addOutput: assetReaderOutput];
NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [dirs objectAtIndex:0];
NSString *exportPath = [[documentsDirectoryPath stringByAppendingPathComponent:str] retain];
if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
}
NSString *Newpath = [[NSString alloc] initWithFormat:#"%#/%#",documentsDirectoryPath,str];
NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
[[NSFileManager defaultManager] copyItemAtPath:exportPath toPath:Newpath error:nil];
NSURL *theFileUrl = [NSURL URLWithString:Newpath];
NSLog(#"theFileUrl: %#",theFileUrl);
NSLog(#"Newpath: %#",Newpath);
NSData *data=[NSData dataWithContentsOfFile:Newpath];
NSLog(#"%d",[data length]);
NSString *eMailBody=[NSString stringWithString:#"I am with you!!!"];
NSString *encodedBody =[eMailBody stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
MFMailComposeViewController *controller =
[[MFMailComposeViewController alloc]init];
controller.mailComposeDelegate = self;
[controller addAttachmentData:data mimeType:#"audio/mp3" fileName:str];
[controller setSubject:sub];
[controller setMessageBody:[NSString stringWithFormat:#"%# ",encodedBody] isHTML:NO];
[self presentModalViewController:controller animated:YES];
[controller release];
/*
// Converts the sound's file path to an NSURL object
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
NSData *data=[[NSData alloc]initWithContentsOfURL:newURL];
NSString *eMailBody=[NSString stringWithString:#"I am with you!!!"];
NSString *encodedBody =[eMailBody stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
MFMailComposeViewController *controller =
[[MFMailComposeViewController alloc]init];
controller.mailComposeDelegate = self;
[controller addAttachmentData:data mimeType:#"audio/x-caf" fileName:#"sound"];
[controller setSubject:sub];
[controller setMessageBody:[NSString stringWithFormat:#"%# ",encodedBody] isHTML:NO];
//[controller setToRecipients:[NSArray arrayWithObject:#"abhishek#iarianatech.com"]];
[self presentModalViewController:controller animated:YES];
[controller release];
*/
}
the image after atachment looks like this
the image after atachment looks like this ![email gets sent but we dont get the attachment in actual mail
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];