iOS开发-音乐播放(AVAudioPlayer)

十度 IOS 2015年12月01日 收藏

现在的手机的基本上没有人不停音乐的,我们无法想象在一个没有声音的世界里我们会过的怎么样,国内现在的主流的主流网易云音乐,QQ音乐,酷狗,虾米,天天基本上霸占了所有的用户群体,不过并没有妨碍大家对音乐的追求,乐流算是突围成功了,据说卖给QQ啦,有兴趣的可以看下。我们做不了那么高大上的就先做个简单的,最核心的就是播放,暂停,切歌,其他的基本上围绕这个修修补补锦上添花的,比如说歌曲名称,专辑,谁听了这首歌。。。铺垫的多了,直接看效果吧,三个按钮一个进度条:

初始化按钮:

 

  1. self.playButton=[[UIButton alloc]initWithFrame:CGRectMake(40, 100, 60, 30)];
  2. [self.playButton setTitle:@"播放" forState:UIControlStateNormal];
  3. [self.playButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  4. [self.playButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
  5. self.playButton.layer.borderColor=[UIColor blackColor].CGColor;
  6. self.playButton.layer.borderWidth=1.0;
  7. self.playButton.layer.cornerRadius=5.0;
  8. [self.playButton addTarget:self action:@selector(playMusic:) forControlEvents:UIControlEventTouchUpInside];
  9. [self.view addSubview:self.playButton];
  10. self.pauseButton=[[UIButton alloc]initWithFrame:CGRectMake(140, 100, 60, 30)];
  11. [self.pauseButton setTitle:@"暂停" forState:UIControlStateNormal];
  12. [self.pauseButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  13. [self.pauseButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
  14. self.pauseButton.layer.borderColor=[UIColor blackColor].CGColor;
  15. self.pauseButton.layer.borderWidth=1.0;
  16. self.pauseButton.layer.cornerRadius=5.0;
  17. [self.pauseButton addTarget:self action:@selector(pauseMusic:) forControlEvents:UIControlEventTouchUpInside];
  18. [self.view addSubview:self.pauseButton];
  19. self.switchButton=[[UIButton alloc]initWithFrame:CGRectMake(240, 100, 60, 30)];
  20. [self.switchButton setTitle:@"切歌" forState:UIControlStateNormal];
  21. [self.switchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  22. [self.switchButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
  23. self.switchButton.layer.borderColor=[UIColor blackColor].CGColor;
  24. self.switchButton.layer.borderWidth=1.0;
  25. self.switchButton.layer.cornerRadius=5.0;
  26. [self.switchButton addTarget:self action:@selector(switchMusic:) forControlEvents:UIControlEventTouchUpInside];
  27. [self.view addSubview:self.switchButton];

 

 初始化进度条:

  1. self.progressView=[[UIProgressView alloc]initWithFrame:CGRectMake(40, 180, 200, 50)];
  2. [self.view addSubview:self.progressView];

 AVAudioPlayer可以看成一个简易播放器,支持多种音频格式,能够进行进度、音量、播放速度等控制,已经满足了基本需求,接下来是播放音乐的代码:

  1. if (self.audioPlayer.isPlaying) {
  2. [self.audioPlayer pause];
  3. }else{
  4. [self loadMusicByAsset:[[AVURLAsset alloc] initWithURL:[[NSBundle mainBundle] URLForResource:@"我最亲爱的" withExtension:@"mp3"] options:nil]];
  5. [self.audioPlayer play];
  6. }

  实例化AVAudioPlayer:

  1. -(void)loadMusicByAsset:(AVURLAsset*)avUrlAsset {
  2. if ([[NSFileManager defaultManager] fileExistsAtPath:avUrlAsset.URL.path]){
  3. NSError *error=nil;
  4. self.audioPlayer= [[AVAudioPlayer alloc] initWithContentsOfURL:avUrlAsset.URL error:&error];
  5. self.audioPlayer.delegate=self;
  6. //准备buffer,减少播放延时的时间
  7. [self.audioPlayer prepareToPlay];
  8. [self.audioPlayer setVolume:1]; //设置音量大小
  9. self.audioPlayer.numberOfLoops =0;//设置播放次数,0为播放一次,负数为循环播放
  10. if (error) {
  11. NSLog(@"初始化错误:%@",error.localizedDescription);
  12. }
  13. }
  14. }

 上面是通过AVURLAsset实例化的,还可以直接通过名称实例化:

  1. -(void)loadMusic:(NSString*)name {
  2. NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:name ofType:@"mp3"]; //创建音乐文件路径
  3. if ([[NSFileManager defaultManager] fileExistsAtPath:musicFilePath]){
  4. NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath];
  5. NSError *error=nil;
  6. self.audioPlayer= [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:&error];
  7. self.audioPlayer.delegate=self;
  8. //准备buffer,减少播放延时的时间
  9. [self.audioPlayer prepareToPlay];
  10. [self.audioPlayer setVolume:1]; //设置音量大小
  11. self.audioPlayer.numberOfLoops =0;//设置播放次数,0为播放一次,负数为循环播放
  12. if (error) {
  13. NSLog(@"初始化错误:%@",error.localizedDescription);
  14. }
  15. }
  16. }

 暂停音乐,这里为了方便单独写了一个按钮,大多数情况下,播放是暂停都是同一个按钮,仅供参考:

  1. -(void)pauseMusic:(UIButton *)sender{
  2. if (self.audioPlayer.isPlaying) {
  3. [self.audioPlayer pause];
  4. }
  5. }

 切歌就是通常大家点的上一曲下一曲,很好理解:

  1. -(void)switchMusic:(UIButton *)sender{
  2. [self.audioPlayer stop];
  3. [self loadMusicByAsset:[[AVURLAsset alloc] initWithURL:[[NSBundle mainBundle] URLForResource:@"我需要一美元" withExtension:@"mp3"] options:nil]];
  4. [self.audioPlayer play];
  5. }

  通过timer实时更新进度条:

  1. self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
  2. selector:@selector(changeProgress)
  3. userInfo:nil repeats:YES];

  进度更新:

  1. -(void)changeProgress{
  2. if (self.audioPlayer.isPlaying) {
  3. self.progressView.progress =self.audioPlayer.currentTime/self.audioPlayer.duration;
  4. }
  5. }

 效果如下:

 音乐播放完成之后可以在AVAudioPlayerDelegate的代理方法里面根据业务场景执行自己安排:

  1. -(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
  2. // [self.timer invalidate];直接销毁,之后不可用,慎重考虑
  3. // [self.timer setFireDate:[NSDate date]]; //继续
  4. // [self.timer setFireDate:[NSDate distantPast]];//开启
  5. [self.timer setFireDate:[NSDate distantFuture]];//暂停
  6. }

  基本上最常用就这么多了,周末愉快~