How to play wav file from directory path - objective-c

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

Related

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

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;
}

How to play audio file of URL link using AVAudioPlayer in iphone objective-c

I am creating a voice communication feature in my application that sends voice notes between users via a web server, however during
testing I am experiencing an error with playing back message I created
with AVAudioPlayer. The AVAudioplayer just returns a null value.
How do I play an audio file from the URL link with AVAudioPlayer?
if (!self.audioRecorder.recording) {
NSURL *url = [NSURL URLWithString:[#"http://.../sound.mp4"]];
NSLog(#"%#", url);
NSLog(#"PlayBack");
NSData *audioData = [NSData dataWithContentsOfURL:url];
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:#"sound1.caf"];
[audioData writeToFile:filePath atomically:YES];
NSError *error;
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
if (self.audioPlayer == nil) {
NSLog(#"%#", [error description]);
NSLog(#"%#", [self.audioPlayer description]);
}else
[self.audioPlayer play];
}else [self.audioRecorder stop];
please try out this code:
- (void) playMessageSound : (NSString *) filename{
self.soundFilename = filename;
//[[RBDMuteSwitch sharedInstance] detectMuteSwitch];
NSString *name = [filename stringByDeletingPathExtension];
NSString *extension = [filename pathExtension];
NSString *filePath = [[NSBundle mainBundle]pathForResource:name ofType:extension];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:&error];
self.audioPlayer.numberOfLoops = 0;
self.audioPlayer.volume = 1.0;
[self.audioPlayer play];
}
check this
NSString* resourcePath = #""; //your url
NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]];
NSError *error;
app.audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
app.audioPlayer.numberOfLoops = 0;
app.audioPlayer.volume = 4.0f;
[app.audioPlayer prepareToPlay];
if (app.audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[app.audioPlayer play];

Using apples suggested code isnt excluding files from icloud backup

I have an app that has been rejected 3 times due to icloud backup issues. Apple have written back to say that I need to use there bit of code to exclude the files from being backed up. However this isnt working and i am at wits end.
Here is the code i've used
- (BOOL)downloadFile:(NSString *)fileURI targetFolder:(NSString *)targetFolder targetFilename:(NSString *) targetFilename{
#try{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:fileURI];
if(![url setResourceValue:#"YES" forKey:NSURLIsExcludedFromBackupKey error:&error]){
NSLog(#"KCDM: Error excluding %# from backup %#", fileURI, error);
}else{
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingString:targetFolder];
NSError *error = nil;
if(![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error];
}
NSString *filePath = [NSString stringWithFormat:#"%#/%#%#", documentsDirectory,targetFolder,targetFilename];
return [urlData writeToFile:filePath atomically:YES];
}
}
}
#catch(NSException * e){
NSLog(#"Error download: %#",e);
}
return false;
}
what am i doing wrong?
You try to set NSURLIsExcludedFromBackupKey for the http://-Url you download from the web. That won't work.
You have to set this key-value pair for the actual file that is saved on the device.
Additionally you are not supposed to set this value to the string #"YES", you must use a NSNumber object representing the boolean value YES.
For example:
NSString *filePath = [NSString stringWithFormat:#"%#/%#%#", documentsDirectory,targetFolder,targetFilename];
if ([urlData writeToFile:filePath atomically:YES]) {
// did write correctly
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
if(![fileURL setResourceValue:#YES forKey:NSURLIsExcludedFromBackupKey error:&error]){
NSLog(#"KCDM: Error excluding %# from backup %#", fileURI, error);
return NO;
}
// could set NSURLIsExcludedFromBackupKey
return YES;
}
// could not write to file
return NO;

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_;
}

Getting the contents of a file in Xcode

In my project I have a plain text file called GAME.js, and I'm trying to get the contents of the file.
[NSString stringWithContentsOfFile:#"GAME.js" encoding:NSUTF8StringEncoding error:nil];
sounds like it should work, but it's just returning an empty string.
Please help me fix this.
Put GAME.js into the Resources folder in your Xcode project and use the following code to get the contents of the file.
NSError *error = nil;
NSString* path = [[NSBundle mainBundle] pathForResource:#"GAME" ofType:#"js"];
NSString* gameFileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
If you pass in a NSError it will tell you exactly what the problem is:
NSError *error = nil;
NSString *myString = [NSString stringWithContentsOfFile:#"GAME.js" encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
NSLog(#"%#", myString);
}
NSError Documentation
Also, check to see if it is in your documents directory which can be accessed with NSSearchPathForDirectoriesInDomains:
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fullPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"GAME.js"];
NSString *myString = [NSString stringWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%# - %#", [error localizedDescription], [error localizedFailureReason]);
} else {
NSLog(#"%#", myString);
}