@interface ViewController ()
@end
@implementation ViewController
//创建按钮、播放器和标志位;
UIButton* button;
AVAudioPlayer* pl;
int flag=0;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typicallyfrom a nib.
//设置按钮类型为0表示自定义,1为矩形圆边白底
button=[UIButtonbuttonWithType:0];
//设置按钮位置和像素;
button.frame=CGRectMake(110,190, 100, 100);
//设置按钮的初始背景图片
[buttonsetBackgroundImage:[UIImageimageNamed:@"play.jpg"]forState:UIControlStateNormal];
//把按钮加到视图
[self.viewaddSubview:button];
//为按钮添加响应机制
[buttonaddTarget:selfaction:@selector(playMusic)forControlEvents:UIControlEventTouchUpInside];
//获取音频路径
NSString* path=[[NSBundlemainBundle]pathForResource:@"music"ofType:@"mp3"];
//把路径转换为网络路径
NSURL* url=[[NSURLalloc] initFileURLWithPath:path];
//生成一个播放器
pl=[[AVAudioPlayeralloc] initWithContentsOfURL:urlerror:nil];
pl.delegate=self;
}
//按钮响应要执行的方法
-(void)playMusic{
if(flag==0) {
[buttonsetBackgroundImage:[UIImageimageNamed:@"pause.jpg"]forState:UIControlStateNormal];
flag=1;
[pl play];
}else{
[buttonsetBackgroundImage:[UIImageimageNamed:@"play.jpg"]forState:UIControlStateNormal];
flag=0;
[pl pause];
}
}
//当音乐播放完后会执行这个方法
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{
//让音乐循环播放
[plplay];
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose ofany resources that can be recreated.
}
@end
//ViewController.h文件
#import
//要实现音频播放必须导入框架。
//导入方法是找到ButtenDemo---TARGETS---ButtenDemo---BuildPhases---Link Binary WithLibraries目录;在里面找到框架添加就好了。
#import
//导入音乐播放代理
@interface ViewController :UIViewController<</span>AVAudioPlayerDelegate>
@end
好了。就改了ViewController.h和ViewController.m两个文件。最后别忘了把名为music.mp3,play.jpg和pause.jpg的3个素材拖到和这些.h/.m的文件同一个目录下。