AVAudioPlayer实现本地音频的播放


1.使用AVAudioPlayer需要先导入AVFoundation系统库,接下来随意找一首歌曲,拉进工程的目录下,我这里用的是薛之谦的一首歌,准备工作完毕,开始写代码。
2.在ViewController.h做以下操作
  #import 
  #import 
 @interface ViewController : UIViewController
 {
    AVAudioPlayer *avAudioPlay;
    UIProgressView *progress;
    UISlider *volimSlider;
    NSTimer *timer;
 }
3.接下来在.m中完成功能的实现
3.1按钮以及进度条的创建
  - (void)CreatBt
{

//初始化三个button
NSArray *TitleArr = @[@"开始",@"暂停",@"结束"];
for (int i =0; i<3; i++)
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:CGRectMake(150, 180+50*i, 60, 40)];
    button.tag = i+1;
    [button setTitle:TitleArr[i] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(btclick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

//读取音频文件
NSURL *url =[[NSBundle mainBundle]URLForResource:@"我好像在哪见过你.mp3" withExtension:nil];
//添加播放器
avAudioPlay = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
avAudioPlay.delegate = self;
//设置循环次数,这里-1代表无限循环
avAudioPlay.numberOfLoops = -1 ;
//预播放
[avAudioPlay prepareToPlay];
//音频播放进度条
progress = [[UIProgressView alloc]initWithFrame:CGRectMake(90, 100, 200, 20)];

[self.view addSubview:progress];
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(PLAYPROGRESS) userInfo:nil repeats:YES];
//音量控制

volimSlider = [[UISlider alloc]initWithFrame:CGRectMake(90, 120, 200, 20)];
volimSlider.minimumValue = 0.0f;
volimSlider.maximumValue = 10.0f;
volimSlider.value = 5.0f;
[self.view addSubview:volimSlider];
UISwitch *switc =[[UISwitch alloc]initWithFrame:CGRectMake(160, 40, 60, 40)];
[switc addTarget:self action:@selector(onOrOff:) forControlEvents:UIControlEventValueChanged];
switc.on = YES;
[self.view addSubview:switc];

}
3.2按钮的点击方法的实现
  - (void)PLAYPROGRESS
{
     progress.progress = avAudioPlay.currentTime/avAudioPlay.duration;

}

- (void)onOrOff:(UISwitch *)sender
 {
     avAudioPlay.volume = sender.on;

}
- (void)volumeChange
{
     avAudioPlay.volume = volimSlider.value;

}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
     //暂停定时器
     [timer setFireDate:[NSDate distantFuture]];


}

PS:下次打开的时候在ViewWillAppear里实现定时器的打开
- (void)viewWillAppear:(BOOL)animated
{
[timer setFireDate:[NSDate distantPast]];

}
4.附效果图:
AVAudioPlayer实现本地音频的播放_第1张图片
音乐播放

你可能感兴趣的:(AVAudioPlayer实现本地音频的播放)