点击UIButton时如何播放MP3?

时间:2010-12-26 02:27:05

标签: ios4 uibutton mp3 avaudioplayer iphone

任何人都可以给我一个关于如何点击UIButton播放声音的示例代码吗?

我想使用AVAudioPlayer播放MP3文件

2 个答案:

答案 0 :(得分:1)

这样的事情应该让你开始。将其添加到视图控制器,然后将按钮挂钩到界面构建器中的playAudio操作。

标题中的

.h

#import <AVFoundation/AVFoundation.h>

@interface ClassName {
    ...
    AVAudioPlayer *audioPlayer;
}
@property (nonatomic, retain) AVAudioPlayer *audioPlayer;

- (IBAction) playAudio;
你的.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]
}

答案 1 :(得分:0)

//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.