iOS App中实现播放音效和音乐功能的简单示例

2020-01-14 22:32:38王冬梅
iOS,音效,音乐

开始写代码之前,我们找一首歌曲放到项目中
这里我们放一首比较经典的歌曲 周华健的 朋友

iOS,音效,音乐

同样我们还是打开项目默认生成的ViewController.m 在里面添加播放功能
首先,导入头文件

复制代码
#import <AVFoundation/AVFoundation.h> 
接下来,创建个控件
复制代码
@property (nonatomic,strong) AVAudioPlayer *audioPlayer;//播放器  
@property (strong, nonatomic) UIProgressView *playProgress;//播放进度  
@property (strong, nonatomic) UIButton *playOrPause; //播放/暂停按钮(如果tag为0认为是暂停状态,1是播放状态)  
  
@property (strong ,nonatomic) NSTimer *timer;//进度更新定时器  
初始化界面
复制代码
- (void)viewDidLoad {  
    [super viewDidLoad];  
    // Do any additional setup after loading the view, typically from a nib.  
    self.view.backgroundColor=[UIColor lightGrayColor];  
    [self initUserFace];  
      
}  
  
-(void)initUserFace{  
      
    //添加playProgress  
      
    _playProgress= [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleDefault];  
      
    _playProgress.frame=CGRectMake(0, 100, self.view.bounds.size.width, 36);  
      
    [self.view addSubview:_playProgress];  
      
    //添加播放按钮  
    _playOrPause=[[UIButton alloc]initWithFrame:CGRectMake(0, 150, 120, 36)];  
    [_playOrPause setTitle:@"播放" forState:UIControlStateNormal];