Search code examples
ios4uibuttonmp3avaudioplayeriphone

how to play an MP3 when a UIButton is tapped?


Can anyone please give me sample code of how sound is played with a UIButton being tapped?

I would like to play an MP3 file using AVAudioPlayer


Solution

  • something like this should get you started. Add this to your view controller, then hook up the button to the playAudio action in interface builder.

    in your header .h

    #import <AVFoundation/AVFoundation.h>
    
    @interface ClassName {
        ...
        AVAudioPlayer *audioPlayer;
    }
    @property (nonatomic, retain) AVAudioPlayer *audioPlayer;
    
    - (IBAction) playAudio;
    

    in your .m

    @synthesize audioPlayer;
    
    - (IBAction) playAudio {
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"audio" withExtension: @"m4a"];
        if (!url){NSLog(@"file not found"); return;}
        NSError *error;
        self.audioPlayer = [[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error] autorelease];
        [audioPlayer play]
    }