Search code examples
iosobjective-cavfoundationnsurl

How to access file using pathForResource:ofType:inDirectory


I have an mp3 file in my Supporting Files folder which I would like to play in my app on a loop. I am using the following code to attempt this:

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"smoothjazz" ofType:@"mp3" inDirectory:@"Supporting Files"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //infinite
[player play];  

However, this returns an error saying:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'  

How can I access my file in supporting files, and play it as intended? All help appreciated.

EDIT: SOLVED! See my answer for how I did it :)


Solution

  • If Supporting Files folder is the Supporting Files group you see in every Xcode project by default than the inFolder: argument is not needed as Supporting Files is a Xcode grouping and not a real folder. So you should do:

    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"smoothjazz" 
                                                              ofType:@"mp3"];
    

    This should work.

    Hope it helps.