mp4 video recorded from iPhone 8 not playing iPad mini 2 & website - objective-c

I am capturing video using UIImagePickerController. Exporting video into mp4. Code is here:
- (NSString *)convertMOVToMp4:(NSURL *)url : (NSString *)filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *dataPath = [documentsPath stringByAppendingPathComponent:#"/doctorphoto"];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *videoPath1 = [dataPath stringByAppendingPathComponent:#"xyz2.mov"]; //Add the file name
NSString *movfilepath = videoPath1;
NSURL *videoURL = url;
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
[videoData writeToFile:videoPath1 atomically:NO];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:movfilepath] options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality])
{
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetPassthrough];
videoPath1 = [self getLocalVideoPath:filename];
exportSession.outputURL = [NSURL fileURLWithPath:videoPath1];
NSLog(#"videopath of your mp4 file = %#",videoPath1); // PATH OF YOUR .mp4 FILE
exportSession.outputFileType = AVFileTypeMPEG4;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed:
NSLog(#"Export failed: %#", [[exportSession error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(#"Export canceled");
break;
default:
NSLog(#"Export success.");
[self.delegate onCompleteConvert: videoPath1 : anyobj];
break;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:movfilepath error:NULL];
}];
}
return videoPath1;
}
Its converting into mp4. Then uploading into AWS server. This link is streaming into iPhone 8, but not playing in iPhone 5S, iPad mini2. In website, audio is playing, but showing black screen.If I follow the same procedure from iPhone 5S or iPad mini, its working fine. Can anybody help me. Thanks in advance.

This change solved the problem:
- (NSString *)convertMOVToMp4:(NSURL *)url : (NSString *)filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *dataPath = [documentsPath stringByAppendingPathComponent:#"/doctorphoto"];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *videoPath1 = [dataPath stringByAppendingPathComponent:#"xyz2.mov"]; //Add the file name
NSString *movfilepath = videoPath1;
NSURL *videoURL = url;
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
[videoData writeToFile:videoPath1 atomically:NO];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:movfilepath] options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality])
{
NSString *preset = AVAssetExportPreset1920x1080;
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:preset];
videoPath1 = [self getLocalVideoPath:filename];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// videoPath1 = [NSString stringWithFormat:#"%#/doctorphoto/%#", [paths objectAtIndex:0], filename];
exportSession.outputURL = [NSURL fileURLWithPath:videoPath1];
NSLog(#"videopath of your mp4 file = %#",videoPath1); // PATH OF YOUR .mp4 FILE
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse = true;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed:
NSLog(#"Export failed: %#", [[exportSession error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(#"Export canceled");
break;
default:
NSLog(#"Export success.");
[self.delegate onCompleteConvert: videoPath1 : anyobj];
break;
}
// UISaveVideoAtPathToSavedPhotosAlbum(videoPath1, self, nil, nil);
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:movfilepath error:NULL];
}];
}
return videoPath1;
}

Related

Cut AVAsset faster

I have this code to cut my AVAsset Video:
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:_url options:nil];
[[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:#"%#",_url] error:nil];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *outputURL = paths[0];
NSFileManager *manager = [NSFileManager defaultManager];
[manager createDirectoryAtPath:outputURL withIntermediateDirectories:YES attributes:nil error:nil];
outputURL = [outputURL stringByAppendingPathComponent:#"output.mp4"];
[manager removeItemAtPath:outputURL error:nil];
exportSession.outputURL = [NSURL fileURLWithPath:outputURL];
exportSession.shouldOptimizeForNetworkUse = YES;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
CMTime start = CMTimeMakeWithSeconds(slider.min*(videoDuration-1), 600);
CMTime duration = CMTimeMakeWithSeconds(slider.max*(videoDuration-1), 600);
CMTimeRange range = CMTimeRangeMake(start, duration);
exportSession.timeRange = range;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void) {
switch (exportSession.status) {
case AVAssetExportSessionStatusCompleted:
_url = [NSURL URLWithString:[NSString stringWithFormat:#"file://%#",outputURL]];
break;
default:
break;
}
}];
The problem: It takes a while to save the AVAsset to the URL and reload it. Is it possible to make it faster?
You could use AVAssetExportPresetPassthrough as your preset name, instead of AVAssetExportPresetHighestQuality. You may be able to avoid an expensive transcode that way. Setting a time range may preclude this for some formats, but it's worth trying.

How do I download an image from a URL and save it to my computer?

How would I download an image from a URL, and have that saved to the computer using Objective-C? This is what I got so far:
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage *imageFromURL = [self getImageFromURL:#"https://www.google.com/images/srpr/logo11w.png"];
[self saveImage:imageFromURL withFileName:#"Google Logo" ofType:#"png" inDirectory:documentsDirectoryPath];
UIImage *imageFromWeb = [self loadImage:#"Google Logo" ofType:#"png" inDirectory:documentsDirectoryPath];
Xcode complains about UIIMage, trying to replace with NSImage. It also complains about an undeclared identifier 'self'.
I need to make an HTTP call to perform this as well. Explain this to me like I'm 5.
Here is the code to Save the image into document Directory.
-(void)saveImagesInLocalDirectory
{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imgName = #"image.png";
NSString *imgURL = #"www.example.com/image/image.png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:imgName];
if(![fileManager fileExistsAtPath:writablePath]){
// file doesn't exist
NSLog(#"file doesn't exist");
if (imgName) {
//save Image From URL
[self getImageFromURLAndSaveItToLocalData:imgName fileURL:imgURL inDirectory:documentsDirectoryPath];
}
}
else{
// file exist
NSLog(#"file exist");
}
}
-(void) getImageFromURLAndSaveItToLocalData:(NSString *)imageName fileURL:(NSString *)fileURL inDirectory:(NSString *)directoryPath {
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
NSError *error = nil;
[data writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", imageName]] options:NSAtomicWrite error:&error];
if (error) {
NSLog(#"Error Writing File : %#",error);
}else{
NSLog(#"Image %# Saved SuccessFully",imageName);
}
}
And this is the one method code..
-(void)saveImagesInLocalDirectory
{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imgName = #"image.png";
NSString *imgURL = #"www.example.com/image/image.png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:imgName];
if(![fileManager fileExistsAtPath:writablePath]){
// file doesn't exist
NSLog(#"file doesn't exist");
//save Image From URL
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]];
NSError *error = nil;
[data writeToFile:[documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", imgName]] options:NSAtomicWrite error:&error];
if (error) {
NSLog(#"Error Writing File : %#",error);
}else{
NSLog(#"Image %# Saved SuccessFully",imgName);
}
}
else{
// file exist
NSLog(#"file exist");
}
}
This is my solution!
+(BOOL)downloadMedia :(NSString*)url_ :(NSString*)name{
NSString *stringURL = url_;
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,name];
[urlData writeToFile:filePath atomically:YES];
return YES;
}
return NO;
}
+(UIImage*)loadMedia :(NSString*)name{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *img_ = [UIImage imageWithContentsOfFile:getImagePath];
return img_;
}

UIImage gives nil

I'm quite new to iOS development. My app gets a file over a network, writes it as image.png and later on reads and displays the image. However, the display part is not working as my UIImage object is always set to nil (on the iOS simulator). I've tried implementing other answers from stackoverflow, but no luck.
Here's my code to save the file:
//inside utility class for model
NSFileHandle * handle = nil;
//For first packet of new file request
if(CountFileParts == 1)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"image.png"];
NSLog(#"%#",appFile);
handle = [NSFileHandle fileHandleForWritingAtPath:appFile];
if(handle == nil)
{
[[NSFileManager defaultManager] createFileAtPath:appFile contents:nil attributes:nil];
handle = [NSFileHandle fileHandleForWritingAtPath:appFile];
}
}
//For other incoming packets of the same request
else
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"image.png"];
//NSLog(#"%#",appFile);
handle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
[handle seekToEndOfFile];
//NSLog(#"Writing continue in new file");
}
if(handle == nil)
NSLog(#"handle nil");
NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
[handle writeData:data];
[handle closeFile];
if(index != -1 && index!= NSNotFound)
{
NSLog(#"Inside Bool");
self.isPlotReady = YES;//kvo in view-controller as shown below
self.isPlotReady = NO;
}
Here's my code to load the image file:
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:#"isPlotReady"])
{
self.isReady = [[change objectForKey:NSKeyValueChangeNewKey] boolValue];
[self updateUI];
}
}
-(void) updateUI
{
if(self.isReady)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self lsOwnDirectory:documentsDirectory];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"image.png"];
//NSLog(#"%#",appFile);
UIImage *img = [UIImage imageWithContentsOfFile:appFile];
if(img == nil)
NSLog(#"Couldn't find image");
else
{
UIImageView *imageView = [[UIImageView alloc] initWithImage:img] ;
[self.view addSubview:imageView];
}
}
}
//Prints Directory contents of input directory
- (void) lsOwnDirectory:(NSString *) currentpath {
NSError * error = [[NSError alloc] init];
NSFileManager *filemgr;
filemgr = [[NSFileManager alloc] init];
//currentpath = [filemgr currentDirectoryPath];
NSLog(#"Current Directory Path : %#",currentpath);
NSArray * files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:currentpath error: &error];
for(NSString * file in files){
NSLog(#"%#", file);
}
}
It alway's prints "Couldn't find image" corresponding to the if statement, but I've seen the file is still there (lsOwnDirectory prints directory contents). Maybe I'm doing something basic wrong here. Thanks in advance.

How to play wav file from directory path

I am trying to play wav file from my directory path which I saved in there before, but I can't play, I hope someone can help me
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *directoryPath = [paths objectAtIndex:0];
directoryPath =[NSString stringWithFormat:#"%#/%#",directoryPath,#"path1.wav",nil];
audioPath1 = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:directoryPath] error:NULL];
[audioPath1 play];
Should be Something like that,
-(void)playFileAdv:(NSString *)audioFile WithVolume:(float)audioLevelIndex{
[self stopAlert];
pSound = [[NSSound alloc]initWithContentsOfFile:audioFile byReference:NO];
playRecursively = NO;
[pSound setVolume:audioLevelIndex];
[pSound setDelegate:self];
[pSound play];
}
if ([[NSFileManager defaultManager] fileExistsAtPath:directoryPath]) {
NSError *error = nil;
audioPath1 = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:directoryPath] error:&error];
if (!error) {
[audioPath1 play];
}
else {
NSLog(#"Error in creating audio player:%#",[error description]);
}
}
else {
NSLog(#"File doesn't exists");
}
Use the above code and show us the console logs

Merge audio and video/image to create a movie file

I want to merge an Audion CAF file and a video/image UIImage to create a movie file (in .mov format).
Say that my audio is 30 seconds long and I have a UIImage; I want to create a .mov file such that the UIImage is displayed the entire time the audio is playing.
I found this reference:
How to add audio to video file on iphone SDK
Can anyone tell me, is it helpful in my case, since the length of my audio and image/video is different?
Thanks in advance.
Yes, you should use AVMutableComposition. To create the video track from your UIImage use AVAssetWriter.
Quicktime Pro can do this. Done that for my own app.
You create the movie from the images. Quicktime offers to read a sequence of images and creates a movie from it. He ask for the FPS during import as well.
The audio track can then simply merged, pasted somewhere or scaled to a selected range of the movie.
use this i found this somewhere in net, i don't remember,....
NSString *fileNamePath = #"audio.caf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *oldappSettingsPath = [documentsDirectory stringByAppendingPathComponent:fileNamePath];
NSURL *audioUrl = [NSURL fileURLWithPath:oldappSettingsPath];
NSString *fileNamePath1 = #"output.mp4";
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
NSString *oldappSettingsPath1 = [documentsDirectory1 stringByAppendingPathComponent:fileNamePath1];
NSLog(#"oldpath=%#",oldappSettingsPath);
NSURL *videoUrl = [NSURL fileURLWithPath:oldappSettingsPath1];
if (avPlayer.duration >0.00000)
{
NSLog(#"SOMEDATA IS THERE ");
AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audioUrl options:nil];
AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:videoUrl options:nil];
AVMutableComposition* mixComposition = [AVMutableComposition composition];
NSLog(#"audio =%#",audioAsset);
AVMutableCompositionTrack *compositionCommentaryTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];
AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:kCMTimeZero error:nil];
AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetPassthrough];
NSString* videoName = #"export.mov";
NSString *exportPath = [NSTemporaryDirectory() stringByAppendingPathComponent:videoName];
NSURL *exportUrl = [NSURL fileURLWithPath:exportPath];
if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath])
{
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
}
_assetExport.outputFileType = #"com.apple.quicktime-movie";
NSLog(#"file type %#",_assetExport.outputFileType);
_assetExport.outputURL = exportUrl;
_assetExport.shouldOptimizeForNetworkUse = YES;
[_assetExport exportAsynchronouslyWithCompletionHandler:
^(void )
{
NSString *fileNamePath = #"sound_record.mov";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *oldappSettingsPath = [documentsDirectory stringByAppendingPathComponent:fileNamePath];
// if ([[NSFileManager defaultManager] fileExistsAtPath:oldappSettingsPath]) {
//
// NSFileManager *fileManager = [NSFileManager defaultManager];
// [fileManager removeItemAtPath: oldappSettingsPath error:NULL];
//
// }
NSURL *documentDirectoryURL = [NSURL fileURLWithPath:oldappSettingsPath];
[[NSFileManager defaultManager] copyItemAtURL:exportUrl toURL:documentDirectoryURL error:nil];
[audioAsset release];
[videoAsset release];
[_assetExport release];
}
];