Search code examples
cocoamp3core-audio

How do you play an mp3 in a Mac Application in Xcode 4.2


I'm trying to play an mp3 in a Mac Application in Xcode 4.2. How would I do this?


Solution

  • You are not giving us much to work with...

    If you just want a simple sound, use NSSound:

    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"fn" ofType:@"mp3"];
    NSSound *sound = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES];
    [sound play];
    // wait for the sound to play before you release these...
    

    With NSSound, the sound plays concurrently with your code. A common mistake is to release the sound or resource while it is still playing. Don't do that.

    You can also use QTMovie in QTKit:

    NSError *err = nil;
    QTMovie *sound = [[QTMovie movieWithFile:@"fn.mp3" error:&err] retain];
    [sound play];
    

    For more demanding sounds, use CoreAudio