iOS开发-音乐播放(AVAudioPlayer)

简介:

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

初始化按钮:

 

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

 

 初始化进度条:

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

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

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

  实例化AVAudioPlayer:

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

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

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

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

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

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

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

  通过timer实时更新进度条:

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

  进度更新:

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

 效果如下:

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

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

本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/4540286.html,如需转载请自行联系原作者

 

相关文章
|
1月前
|
API 数据安全/隐私保护 iOS开发
利用uni-app 开发的iOS app 发布到App Store全流程
利用uni-app 开发的iOS app 发布到App Store全流程
87 3
|
3月前
|
存储 iOS开发
iOS 开发,如何进行应用的本地化(Localization)?
iOS 开发,如何进行应用的本地化(Localization)?
122 2
|
8天前
|
API 定位技术 iOS开发
IOS开发基础知识:什么是 Cocoa Touch?它在 iOS 开发中的作用是什么?
【4月更文挑战第18天】**Cocoa Touch** 是iOS和Mac OS X应用的核心框架,包含面向对象库、运行时系统和触摸优化工具。它提供Mac验证的开发模式,强调触控接口和性能,涵盖3D图形、音频、网络及设备访问API,如相机和GPS。是构建高效iOS应用的基础,对开发者至关重要。
11 0
|
23天前
|
开发工具 Swift iOS开发
利用SwiftUI构建动态用户界面:iOS开发新范式
【4月更文挑战第3天】 随着苹果不断推进其软件开发工具的边界,SwiftUI作为一种新兴的编程框架,已经逐渐成为iOS开发者的新宠。不同于传统的UIKit,SwiftUI通过声明式语法和强大的功能组合,为创建动态且响应式的用户界面提供了一种更加简洁高效的方式。本文将深入探讨如何利用SwiftUI技术构建具有高度自定义能力和响应性的用户界面,并展示其在现代iOS应用开发中的优势和潜力。
|
2月前
|
监控 API Swift
用Swift开发iOS平台上的上网行为管理监控软件
在当今数字化时代,随着智能手机的普及,人们对于网络的依赖日益增加。然而,对于一些特定场景,如家庭、学校或者企业,对于iOS设备上的网络行为进行管理和监控显得尤为重要。为了满足这一需求,我们可以利用Swift语言开发一款iOS平台上的上网行为管理监控软件。
196 2
|
3月前
|
数据可视化 iOS开发
iOS 开发,什么是 Interface Builder(IB)?如何使用 IB 构建用户界面?
iOS 开发,什么是 Interface Builder(IB)?如何使用 IB 构建用户界面?
40 4
|
3月前
|
iOS开发
iOS开发解释 App 生命周期,包括各个阶段的调用顺序。
iOS开发解释 App 生命周期,包括各个阶段的调用顺序。
28 1
|
iOS开发
iOS开发拓展篇—音乐的播放
iOS开发拓展篇—音乐的播放 一、简单说明   音乐播放用到一个叫做AVAudioPlayer的类,这个类可以用于播放手机本地的音乐文件。 注意:   (1)该类(AVAudioPlayer)只能用于播放本地音频。
797 0
|
3月前
|
存储 数据建模 数据库
IOS开发数据存储:什么是 UserDefaults?有哪些替代方案?
IOS开发数据存储:什么是 UserDefaults?有哪些替代方案?
39 0