#import "ViewController.h"#import@interface ViewController ()@property (nonatomic, strong)AVAudioPlayer *player;@property (nonatomic, weak)UILabel *timer;@property (nonatomic, strong)NSTimer *t;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // 首先创建一个label用来显示音乐的总时长和当前的时间; UILabel *timer = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,100, 30)]; self.timer = timer; timer.textAlignment = NSTextAlignmentCenter; self.timer.center = self.view.center; [self.view addSubview:timer];// 获取音乐文件的url; NSString *path = [[NSBundle mainBundle]pathForResource:@"Groove Coverage-Runaway" ofType:@"mp3"]; NSURL *url = [NSURL fileURLWithPath:path]; NSError *error = nil;// 创建一个播放对象; AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error]; if (error) { NSLog(@"创建播放对象失败:%@",error); return; }else { self.player = player;// 这一步必须执行,只有各就各位(创建播放对象)、预备(prepareToPlay:准备播放)之后发令枪才会响起(才能够play); [self.player prepareToPlay]; }}//定时自动调用的方法,用于随时设置label显示的播放时间。- (void)setUpTimer { //isPlaying为BOOL属性,播放对象是否正在播放。 if (self.player.isPlaying) {// self.player.currentTime,如果player正在播放此属性为当前的播放时间,也可以设置player的播放偏移(便宜到指定的时间点 开始播放)。// self.player.duration,此属性为player播放音乐的总时长。 self.timer.text = [NSString stringWithFormat:@"%d:%d/%d:%d",(int)self.player.currentTime/60,(int)self.player.currentTime%60,(int)self.player.duration/60,(int)self.player.duration%60]; }else { self.timer.text = @"等待播放"; }}-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if (self.player.isPlaying) { [self.t invalidate];// pause 暂停;还有十个stop的方法,但是现在与pause等效了。 [self.player pause]; }else { NSTimer *t = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(setUpTimer) userInfo:nil repeats:YES]; self.t = t;// play:播放。 [self.player play]; }}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
当然除了这些还有
volume:设置声音的大小为float值取值范围为0.0-1.0;
enableRate:BOOL是否可已设置音乐的播放速率;
rate:float在enableRate设置为YES时可以设置音乐的播放速率,默认为1,0.5即为半速,2.0即为双倍速。
numberOfLoops:loop即为循环。number是次数。由此可证numberOfLoops即为循环次数。。。