Search code examples
xcodemacosmp3

OS X - Play mp3 outside of mainBundle


I would like to play an mp3 file outside of the mainBundle (from any location on the hard-drive).

That was my attempt (doesn't work):

NSString* theFileName = [filepath stringByDeletingPathExtension];

NSLog(@"%@", theFileName); // -> /Volumes/Data%20HD/Music/iTunes/Music/Linkin%20Park/Hybrid%20Theory/01%20Papercut

NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath2 = [mainBundle pathForResource:theFileName ofType:@"mp3" ];
NSData *fileData = [NSData dataWithContentsOfFile:filePath2];
NSError *error2;
audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error2];
[audioPlayer play];

Solution

  • You can use NSSound.

    NSURL* file = [NSURL fileURLWithPath:@"/Music/1.mp3"];
    NSSound *sound = [[NSSound alloc] initWithContentsOfURL:file byReference:NO];
    [sound play];