How to get the file system path for a resource on an iPhone?

On the iPhone, I need to get the path to the resource. Ok, I did it, but when it comes to CFURLCreateFromFileSystemRepresentation, I just don't know how to solve it. Why does this error occur? Any solution or workaround would be much appreciated. Thank you in advance.

I looked at the following examples to play audio using AudioQueue on iPhone: SpeakHere, AudioQueueTools (from the SimpleSDK directory), and AudioQueueTest. I tried to do this and this, trying to combine puzzles. Right now, I'm stuck with this. The program crashed due to an exception thrown from sndFile above.

I use AVAudioPlayer to play every sound in my iPhone games. On a real iPhone device, it turned out to be very laconic when the sound is playing, so I decided to use AudioQueue.

- (id) initWithFile: (NSString*) argv{ if (self = [super init]){ NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:argv ofType:@"mp3"]; int len = [soundFilePath length]; char* fpath = new char[len]; //this is for changing NSString into char* to match //CFURLCreateFromFileSystemRepresentation function requirement. for (int i = 0; i < [soundFilePath length]; i++){ fpath[i] = [soundFilePath characterAtIndex:i]; } CFURLRef sndFile = CFURLCreateFromFileSystemRepresentation (NULL, (const UInt8 *)fpath, strlen(fpath), false); if (!sndFile) { NSLog(@"sndFile error"); XThrowIfError (!sndFile, "can't parse file path"); } } 
+4
source share
2 answers

Why do you need CFURL?

If you have a method elsewhere that requires CFURL, you can simply use NSURL thanks to the free bridge connection. So, to create an NSURL, you simply do:

  NSString * soundFilePath = [[NSBundle mainBundle] pathForResource:argv ofType:@"mp3"]; NSURL *soundURL = [NSURL fileURLWithPath:soundFilePath]; 

In general, if you find yourself using CF objects, you are probably doing something wrong.

+11
source

I'm not sure if this will save you from your exception, but there is an easier way to convert NSString to a char array. This is how I write this method:

 - (id) initWithFile:(NSString*) argv { if ((self = [super init]) == nil) { return nil; } NSString * soundFilePath = [[NSBundle mainBundle] pathForResource:argv ofType:@"mp3"]; CFURLRef sndFile = CFURLCreateFromFileSystemRepresentation (NULL, [soundFilePath UTF8String], [soundFilePath length], NO); if (!sndFile) { NSLog(@"sndFile error"); } XThrowIfError (!sndFile, "can't parse file path"); ... } 

Or, since CFURL is a "duty free bridge" with NSURL , you can simply do:

 - (id) initWithFile:(NSString*) argv { if ((self = [super init]) == nil) { return nil; } NSString * soundFilePath = [[NSBundle mainBundle] pathForResource:argv ofType:@"mp3"]; NSURL * sndFile = [NSURL URLWithString:[soundFilePath stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]; if (!sndFile) { NSLog(@"sndFile error"); } XThrowIfError (!sndFile, "can't parse file path"); ... } 
0
source

All Articles