开发者

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


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]
}


//ViewController.h ,write below code
@interface ViewController : UIViewController<AVAudioRecorderDelegate,AVAudioPlayerDelegate>

//assign property to player
 @property(nonatomic,retain) AVAudioPlayer *player;

//then write in ViewController.m file in ViewDidLoad Method

NSError *soundError;
NSString *path=[[NSBundle mainBundle]pathForResource:@"soundFileName" ofType:@"mp3"]; //.mp3 file for player
NSURL *file=[[NSURL alloc]initFileURLWithPath:path]; //path
_player=[[AVAudioPlayer alloc]initWithContentsOfURL:file error:&soundError]; //player Object

if(_player == nil)
{
    NSLog(@"player is empty because of %@",soundError);
}
else
{
    [_player play];
    _player.volume=1.0;
    [_player setDelegate:self];

}

// for stop player you can use 
    // [_player stop]; //uncomment this line when you wants to stop it.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜