AVAudioPlayer error - objective-c

i'm using this code but it's not working;
Import:
#import <AudioToolbox/AudioServices.h>
Header File:
AVAudioPlayer *_audioPlayer;
Code:
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/welcome.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
_audioPlayer.numberOfLoops = 0;
if (_audioPlayer == nil)
{
NSLog(#"%#", [error description]);
}
else
{
[_audioPlayer play];
NSLog(#"PLAY");
}
The NSLog:
Error Domain=NSOSStatusErrorDomain Code=-43 "The operation couldn’t be completed. (OSStatus error -43.)"
it's not working on my iPhone (5.1) iPad (5.0) iPhone 5.0 Simulator.
Anyone know how i can fix this?

You get that error if no file was found at the path you specified.
Also, check that you do have a file welcome.mp3 and that it is bundled with the application target. To do that, select the target, go to Build Phases tab and make sure the file is in the list Copy Bundle Resources. If it is not there, add it.

Related

Error in get file from iCloud in ios

Hi in my app I have to get file from iCloud.. I enable iCloud all working fine in Simulator.. But when I test in iPhone, I can see the iCloud files when I choose the default delegate calls but I can't get data from the url..
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
{
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:url];
}
Always I getting pdfData as nil. I log the error
Error Domain=NSCocoaErrorDomain Code=257 "The operation couldn’t be completed. (Cocoa error 257.)" UserInfo=0x17029810 {NSFilePath=/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/download (2).jpeg, NSUnderlyingError=0x15ea9680 "The operation couldn’t be completed. Operation not permitted"}
I cant figure out.. Can you please help me to fix this issue..
Finally I found answer myself.. by refer this link Here
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
{
[url startAccessingSecurityScopedResource];
__block NSData *pdfData = nil;
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
__block NSError *error;
[coordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
pdfData = [NSData dataWithContentsOfURL:newURL];
}];
[url stopAccessingSecurityScopedResource];
}

iCloud Core Data IOS8 Path is outside of any CloudDocs Container

My iCloud Core Data app was running great on iOS7 and ready to launch. When I test on iOS 8 I get the following error and can't seem to fix it when trying to upload data to iCloud.
I suspect my problem is related to how I am getting the document directory and changes in the doc directory with iOS8 but I just can't figure this out..
014-10-12 15:14:17.862 XXXXXXX [4662:236693] __45-[PFUbiquityFilePresenter processPendingURLs]_block_invoke(439): CoreData: Ubiquity: Librarian returned a serious error for starting downloads Error Domain=BRCloudDocsErrorDomain Code=6 "The operation couldn’t be completed. (BRCloudDocsErrorDomain error 6 - Path is outside of any CloudDocs container, will never sync)" UserInfo=0x7f8b1a525f60 {NSDescription=Path is outside of any CloudDocs container, will never sync, NSFilePath=/Users/garyrea/Library/Developer/CoreSimulator/Devices/9AADFE8E-5ECC-4969-9418-57DA45B747C9/data/Containers/Data/Application/AD2E5E62-7295-4371-A08D-1790E8FCCD96/Documents/CoreDataUbiquitySupport/nobody~simA28745A4-A67F-598C-9260-F9AC36609ECF/iCloud/5B8BFA36-1ACA-4966-B7ED-A7344D36ACF1/container/nobody~simA28745A4-A67F-598C-9260-F9AC36609ECF/iCloud/2trlqdMQVpJ~wlEfiLvjWtQfrUJ8YiNCd84KW_xiw4A=/F0CF5F29-D437-4728-B0A2-C5BB90BBC239.1.cdt} with userInfo {
NSDescription = "Path is outside of any CloudDocs container, will never sync";
NSFilePath = "/Users/garyrea/Library/Developer/CoreSimulator/Devices/9AADFE8E-5ECC-4969-9418-57DA45B747C9/data/Containers/Data/Application/AD2E5E62-7295-4371-A08D-1790E8FCCD96/Documents/CoreDataUbiquitySupport/nobody~simA28745A4-A67F-598C-9260-F9AC36609ECF/iCloud/5B8BFA36-1ACA-4966-B7ED-A7344D36ACF1/container/nobody~simA28745A4-A67F-598C-9260-F9AC36609ECF/iCloud/2trlqdMQVpJ~wlEfiLvjWtQfrUJ8YiNCd84KW_xiw4A=/F0CF5F29-D437-4728-B0A2-C5BB90BBC239.1.cdt";
} for these urls: (
"file:///Users/garyrea/Library/Developer/CoreSimulator/Devices/9AADFE8E-5ECC-4969-9418-57DA45B747C9/data/Containers/Data/Application/AD2E5E62-7295-4371-A08D-1790E8FCCD96/Documents/CoreDataUbiquitySupport/nobody~simA28745A4-A67F-598C-9260-F9AC36609ECF/iCloud/5B8BFA36-1ACA-4966-B7ED-A7344D36ACF1/container/nobody~simA28745A4-A67F-598C-9260-F9AC36609ECF/iCloud/2trlqdMQVpJ~wlEfiLvjWtQfrUJ8YiNCd84KW_xiw4A=/F0CF5F29-D437-4728-B0A2-C5BB90BBC239.1.cdt"
)
my app delegate extension code where I create my persistent store is as follows. I have a seed database for first time installation.
- (NSPersistentStoreCoordinator *)createPersistentStoreCoordinator{
NSPersistentStoreCoordinator *persistentStoreCoordinator = nil;
NSManagedObjectModel *managedObjectModel = [self createManagedObjectModel];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:managedObjectModel];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#
"CoreData.sqlite"];
if (![[NSFileManager defaultManager]fileExistsAtPath:[storeURL path]]){
NSURL *preloadURL=[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"SeedDatabase" ofType:#
"sqlite"]];
NSError *error=nil;
if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&error]){
NSLog(#
"File couldnt save");
}
}
NSUbiquitousKeyValueStore *kvStore=[NSUbiquitousKeyValueStore defaultStore];
if (![kvStore boolForKey:#"SEEDED_DATA"]){
NSLog (#
"In the new database");
NSURL *seedStoreURL=[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"SeedDatabase" ofType:#
"sqlite"]];
NSError *seedStoreErrpr;
NSDictionary *seedStoreOptions=#{NSReadOnlyPersistentStoreOption: #YES};
NSPersistentStore *seedStore=[persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:seedStoreURL options:seedStoreOptions error:&seedStoreErrpr];
NSDictionary *iCloudOptions =#{NSPersistentStoreUbiquitousContentNameKey: #"iCloud",
NSMigratePersistentStoresAutomaticallyOption:#YES,
NSInferMappingModelAutomaticallyOption:#YES
};
NSOperationQueue *queue=[[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
NSError *error;
[persistentStoreCoordinator migratePersistentStore:seedStore toURL:storeURL options:iCloudOptions withType:NSSQLiteStoreType error:&error];
NSLog(#
"Persistant store migrated");
[kvStore setBool:YES forKey:#
"SEEDED_DATA"];
// [self checkForDuplicates];
}];
}else{
NSError *error;
NSDictionary *storeOptions =#{NSPersistentStoreUbiquitousContentNameKey: #
"iCloud"
};
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:storeOptions
error:&error]) {
NSLog(#
"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
return persistentStoreCoordinator;
}
- (NSURL *)applicationDocumentsDirectory{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
I was able to resolve this error by specifying the iCloud drive directory (Same name as the one on the developer.apple.com interface).
-(NSURL *)cloudDirectory
{
NSFileManager *fileManager=[NSFileManager defaultManager];
NSString *teamID=#"iCloud";
NSString *bundleID=[[NSBundle mainBundle]bundleIdentifier];
NSString *cloudRoot=[NSString stringWithFormat:#"%#.%#",teamID,bundleID];
NSURL *cloudRootURL=[fileManager URLForUbiquityContainerIdentifier:cloudRoot];
NSLog (#"cloudRootURL=%#",cloudRootURL);
return cloudRootURL;
}
and including it in the icloudOptions Dictionary as a NSPersistentStoreUbiquitousContentURLKey
NSDictionary *storeOptions =#{NSPersistentStoreUbiquitousContentNameKey: #"iCloud",
NSPersistentStoreUbiquitousContentURLKey:[self cloudDirectory],
};
I was getting some strange errors so I removed the app from all devices, deleted the iCloud drive file and re ran on an actual device and it worked fine. Not sure if it runs on IOS7 now but since I only specified the NSPersistentStoreUbiquitousContentURLKey I am pretty confident it should be fine.
I had the same issue during loading some test data.
For the load of the data I was deleting all records.
To avoid the exception a simple sleep(1) between cleaning and loading was enough.

Asset loading failing (Cocoa for OS X)

I'm very new to mac development and I have a hard time understanding how all this Cocoa stuff works.
Right now I'm working on getting still images from a video file and in order to do so, I need to load my video file (asset).
NSURL *url = [[NSURL alloc]initWithString:#"/Users/EVG/Desktop/myfile.mp4"];
AVURLAsset *myAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
NSArray *keys = #[#"tracks"];
[myAsset loadValuesAsynchronouslyForKeys:keys completionHandler:^()
{
NSError *error = nil;
AVKeyValueStatus tracksStatus = [myAsset statusOfValueForKey:#"tracks" error:&error];
if ( tracksStatus == AVKeyValueStatusFailed ||
tracksStatus == AVKeyValueStatusCancelled )
{
NSLog(#"Failed with error: %#", [error localizedDescription]);
}
}];
After this code is executed I'm getting the following message:
NSView Controller[644:4413] Failed with error: The operation could not be completed
Does anyone know how to solve this problem I'm having?
Thank you!!!
Your URL is wrong. First of all, absolute file paths should begin with a /, as in /Users/EVG/Desktop/myfile.mp4. However, that's not a URL. A file URL should be file:///Users/EVG/Desktop/myfile.mp4.

AVAudioPlayer returns success but no sound from device

I have a very simple app that I have built to test out AVAudioPlayer. I have a 16s aif file that plays just fine on my Mac. Put it in a simple app and ran on my iPhone but no sound. Sending 'play' to the object returns success and audioPlayerDidFinishPlaying comes back with success after 16 seconds. Still no sound. Have checked the sound volume on the iPhone, just fine. Have checked to make sure my AVAudioPlayer object has volume set at 1.0 - it does. Can anybody help?
Here's my code
NSString *soundPath = [[NSBundle mainBundle] pathForResource:#"Soothing" ofType:#"aif"];
NSURL *playURL = [NSURL fileURLWithPath:soundPath];
NSError *error;
self.myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:playURL error:&error];
NSLog(#"About to play sound");
self.myAudioPlayer.delegate = self;
[self.myAudioPlayer prepareToPlay];
bool success = [self.myAudioPlayer play];
if (!success) {
NSLog(#"Failed to play file");
} else NSLog(#"Looks like it succeded");
OK - got it figured out. I had not configured the AVAudioSession for my app. Did something very simple as follows (copied from Apple's example code):
[[AVAudioSession sharedInstance] setDelegate: self];
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
if (setCategoryError)
NSLog(#"Error setting category! %#", setCategoryError);
Sound now plays - plus learned a lot about how to control playback through screen locks, etc., which will be valuable.
Did you check if you get anything from the error?
if(error) {
NSLog( #"%#", [error localizedDescription] );
}

(iOS) Why does AVAudioPlayer initWithContentsOfURL always fail with error code=-43

NSString *songNameEscaped = [songName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *songURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", #"http://somerootpath/Music/", songNameEscaped]];
NSLog(#"songURL = %#", songURL);
NSError *avPlayerError = nil;
AVAudioPlayer *avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:songURL error:&avPlayerError];
if (avPlayerError)
{
NSLog(#"Error: %#", [avPlayerError description]);
}
else
{
[avPlayer play];
}
If I copy the NSLog output from NSLog(#"songURL = %#", songURL); and paste it in safari, Quicktime plugin plays the files no problem so I know the URLs are valid. I've tried with .m4a and .mp3 files and have tried removing the spaces from songName but not matter what I always get Error:
Error Domain=NSOSStatusErrorDomain Code=-43 "The operation couldn’t be completed. (OSStatus error -43.)".
But they are just standard .m4a / .mp3 files created in iTunes.
Apparently AVAudioPlayer doesn't support streaming. Apple recommends AVPlayer for this although it is not as conveinient for finding things like current time and duration .
Error -43 indicates an inability to find the data. This could be because the url was in fact malformed, or because the server doesn't support streaming. You should try to pre-load the song data with an NSData object.
NSString *songNameEscaped = [songName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *songURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", #"http://somerootpath/Music/", songNameEscaped]];
NSLog(#"songURL = %#", songURL);
NSError *avPlayerError = nil;
NSData* songData = [NSData dataWithContentsOfURL:songURL error:&avPlayerError];
if (songData)
{
AVAudioPlayer *avPlayer = [[AVAudioPlayer alloc] initWithData error:&avPlayerError];
if (avPlayer)
{
[avPlayer prepareToPlay];
[avPlayer play];
}
else
{
NSLog(#"Error initializing data for AVAudioPlayer. Possibly an Unsupported Format");
NSLog(#"Error: %#", [avPlayerError description]);
}
}
else
{
NSLog(#"Error initializing data for AVAudioPlayer. Possibly Malformed URL");
NSLog(#"Error: %#", [avPlayerError description]);
}
I had the same problem yesterday. Turns out my url was wrong.
I had something like you here:
NSURL *songURLID = [NSURL URLWithString:[NSString stringWithFormat:#"%#%d", #"http://somerootpath/Music/", songNameEscaped]];
NSLog(#"songURL = **%d**", songURL**ID**);
But, my songURL was of NSString type. My NSLog wrote it correctly but when I put %d in url it turn out wrong. I suggest you try to check out your AVAudioPlayer url again.
try something like described here to see the players url.
You may want to try checking the targets on your audio file. I had a similar issue and fixed it by making sure that my mp4 file target membership check box was checked. I must not have checked it when I was importing the file originally.
in Apple documentation
An instance of the AVAudioPlayer class, called an audio player,
provides playback of audio data from a file or memory.
Apple recommends that you use this class for audio playback unless you
are playing audio captured from a network stream or require very low
I/O latency.