Search code examples
iphoneaudioavfoundationnssound

What's the SIMPLEST way to play a sound clip in an iPhone app?


I want to be able to play a sound clip in an iPhone OS app. I've seen info on both NSSound as well as AVFoundation as being means for getting sound clips played on an iPhone OS device, but I'm still not clear on the subject and could use some help. No need to spell it out for me step-by-step in actual code, but if someone could give me a hint as to the general direction (i.e. which classes I should be focusing on) in which I should start moving I'll fill in the blanks myself. So, what's the SIMPLEST way to play a sound clip in an iPhone app?


Solution

  • Apple has an article on this subject, see: this link

    AVAudioPlayer is the simplest way to play sounds of any length, looping or not, however it requires iPhone OS 2.2 or higher. A simple example:

    NSString *soundFilePath =
                    [[NSBundle mainBundle] pathForResource: @"sound"
                                                    ofType: @"wav"];
    
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
    
    AVAudioPlayer *newPlayer =
                    [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
                                                           error: nil];
    [fileURL release];
    
    [newPlayer play];
    
    [newPlayer release];
    

    It will play virtually any file format (aiff,wav,mp3,aac) Keep in mind that you can only play one mp3/aac file at a time.