views:

35

answers:

2

I have some mp3 files in my resources folder, how can i play those mp3 files? I just know their name.

+2  A: 

You can use the AVAudioPlayer. To get the URL for the files use NSBundles -URLForResource:withExtension: (or downward compatible alternatives, see Kennys answer):

NSURL *url = [[NSBundle mainBundle] URLForResource:@"myFile" withExtension:@"mp3"];
NSError *error = 0;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
// check error ...
[player play];
// ...

And don't forget to read the Multimedia Programming Guides section on using audio.

Georg Fritzsche
+1  A: 

Just to supplement @Georg's answer.

As you can see from the doc, -URLForResource:withExtension: is available only since 4.0. As 3.x is still widespread, it's better to use the backward-compatible methods:

  • By converting a path to NSURL:

    NSString* path = [[NSBundle mainBundle] pathForResource:@"myFile" ofType:@"mp3"];
    NSURL* url = [NSURL fileURLWithPath:path];
    ....
    
  • or, by CoreFoundation methods:

    CFURLRef url = CFBundleCopyResourceURL(CFBundleGetMain(),
                                           CFSTR("myFile"), CFSTR("mp3"), NULL);
    ....
    CFRelease(url);
    
KennyTM
Oops, thats what i get for quickly throwing it together :)
Georg Fritzsche