iOS 音频本地和在线播放器

时间:2022-11-19 16:32:53

#一个完整功能的音乐播放器app开源代码,支持音乐播放的全部功能,包括暂停、前进后退、循环播放、歌词同步显示等等,现在分享一下系统的播放器AVAudioPlay#

1. 打开 ViewControler.h 

#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>

@interface ViewController :UIViewController

@property (nonatomic,retain) AVAudioPlayer *player; // 创建一个播放器

@property (nonatomic,retain) UIButton *button;      // 播放按钮

@property (nonatomic,retain) UIProgressView *progress;//进度显示

@property (nonatomic,retain) NSTimer *time;          // 时间

@property (nonatomic,retain) UISlider *volumeSlider;

@end


2. 打开ViewControler.m

#import "ViewController.h"

#import <AVFoundation/AVFoundation.h>

typedefNS_ENUM(NSInteger, playStatus){

    playStatusNo,

    playStatusYes,

    

};

@interface ViewController ()<AVAudioPlayerDelegate>

@property (nonatomic,assign) playStatus staus;

@property (nonatomic,retain) UISlider *slider;

@property (nonatomic,retain) UILabel *timeLabel;

@end


@implementation ViewController

- (void)dealloc

{

    [_progress release];

    [_buttonrelease];

    [_playerrelease];

    [superdealloc];

}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

   self = [superinitWithNibName:nibNameOrNil bundle:nibBundleOrNil];

   if (self) {

        

    }

    return self;

}

- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.


    // 创建一个播放按钮

    self.button = [[UIButtonalloc] initWithFrame:CGRectMake(100,100, 100, 100)];

    // 给按钮一个颜色,

    _button.backgroundColor = [UIColorredColor];

      // 按钮titile

    [_buttonsetTitle:@"Play"forState:UIControlStateNormal];

     // 把按钮变换成圆角的

    _button.layer.cornerRadius =50;

    _button.layer.masksToBounds =YES;

     // 实现按钮方法

    [_buttonaddTarget:selfaction:@selector(buttonClickStart)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:_button];

    [_buttonrelease];

    // 停止按钮

   UIButton *stop = [[UIButtonalloc] initWithFrame:CGRectMake(100,300, 100, 100)];

    stop.backgroundColor = [UIColorredColor];

    [stop setTitle:@"Stop"forState:UIControlStateNormal];

    stop.layer.cornerRadius =50;

    stop.layer.masksToBounds =YES;

    [stop addTarget:selfaction:@selector(buttonClickStop)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:stop];

    [stoprelease];

    


    //播放本地

//    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"]] error:nil];

    

    // 播放网络

    NSData *mydata=[[NSDataalloc]initWithContentsOfURL:[NSURLURLWithString:@"http://a.ali.dongting.com/494a44568a1c7555/1422090214/m4a_32_9/0b/0c/0b4466a12a5af34259fba0090380da0c.m4a?s=t"]];

    // 初始化播放器,并将url传给播放器

   self.player=[[AVAudioPlayeralloc] initWithData:mydataerror:nil];

    

    // 播放器的代理方法

   _player.delegate =self;

    NSLog(@"currentTime == %f",self.player.currentTime);


    //_player.volume =0.8; //音量 0.0-1.0之间

    [_playerprepareToPlay];//分配播放所需的资源,并将其加入内部播放队列 (预播放)

    

    // 初始化进度条

    //self.progress = [[UIProgressView alloc] initWithFrame:CGRectMake(20, 50, 320, 20)];

    

    self.slider = [[UISlideralloc] initWithFrame:CGRectMake(20,60, 320, 20)];

    self.slider.maximumValue =self.player.duration;

    

    [self.slideraddTarget:selfaction:@selector(sliderValueChanged)forControlEvents:UIControlEventValueChanged];

    [self.viewaddSubview:self.slider];

    [self.sliderrelease];

    

    self.timeLabel = [[UILabelalloc] initWithFrame:CGRectMake(0,0, 50,20)];

    self.timeLabel.backgroundColor = [UIColorredColor];

   self.timeLabel.text =@"0:00";

    

    [self.viewaddSubview:self.timeLabel];

    [self.timeLabelrelease];

    

    

    //  NSTimer来监控音频播放进度

    

    // 预订一个Timer,设置一个时间间隔。表示输入一个时间间隔对象,以秒为单位,一个>0的浮点类型的值,如果该值<0,系统会默认为0.1 self表发送的对象 useInfo此参数可以为nil,当定时器失效时,由你指定的对象保留和释放该定时器 repeatYES时,定时器会不断循环直至失效或被释放,当NO时,定时器会循环发送一次就失效。

    

    _time = [NSTimerscheduledTimerWithTimeInterval:0.1target:selfselector:@selector(updateslider)userInfo:nilrepeats:YES];

    

//    [self.view addSubview:_progress];

//    [_progress release];

    

    // 播放次数

   UISwitch *loop = [[UISwitchalloc] initWithFrame:CGRectMake(100,230, 60, 40)];

    [loop addTarget:selfaction:@selector(loopYesOrNo)forControlEvents:UIControlEventValueChanged];

    loop.on =NO; // 默认状态不打开

    

    [self.viewaddSubview:loop];

    [looprelease];

    

    //初始化音量控制

       self.volumeSlider = [[UISlideralloc] initWithFrame:CGRectMake(20,70, 200, 20)];

         [_volumeSlideraddTarget:selfaction:@selector(volumeChange)forControlEvents:UIControlEventValueChanged];

        //设置最小音量

        _volumeSlider.minimumValue =0.0f;

        //设置最大音量

        _volumeSlider.maximumValue =1.0f;

         //初始化音量为多少

        _volumeSlider.value =0.5f;

    

         [self.viewaddSubview:_volumeSlider];

        [_volumeSliderrelease];

    

    // 声音开关

   UISwitch *volume = [[UISwitchalloc] initWithFrame:CGRectMake(200,230, 60, 40)];

    [volume addTarget:selfaction:@selector(volumeOnOrOff:)forControlEvents:UIControlEventValueChanged];

    volume.on =YES; // 默认状态打开

    

    [self.viewaddSubview:volume];

    [volumerelease];

    

}

- (void)buttonClickStart

{

    

   if (self.staus ==playStatusYes) {

       self.staus =playStatusNo;

        [_playerpause]; // 暂停播放;

        [NSTimerscheduledTimerWithTimeInterval:0.1target:selfselector:@selector(updateMusicTimeLabel)userInfo:selfrepeats:

        YES];

        [_buttonsetTitle:@"暂停播放"forState:UIControlStateNormal];

    }

   else

    {

        [_playerplay]; // 开始播放

       self.staus =playStatusYes;

        [NSTimerscheduledTimerWithTimeInterval:0.1target:selfselector:@selector(updateMusicTimeLabel)userInfo:selfrepeats:

        YES];


        [_buttonsetTitle:@"正在播放"forState:UIControlStateNormal];

    }

}

-(void)updateMusicTimeLabel{

   if ((int)self.player.currentTime %60 < 10) {

       self.timeLabel.text = [NSStringstringWithFormat:@"%d:0%d",(int)self.player.currentTime / 60, (int)self.player.currentTime %60];

    }else {

       self.timeLabel.text = [NSStringstringWithFormat:@"%d:%d",(int)self.player.currentTime / 60, (int)self.player.currentTime %60];

    }

    

//    NSDictionary *dic = self.list[_count];

//    NSArray *array = [dic[@"lrctime"] componentsSeparatedByString:@":"];//把时间转换成秒

//    NSUInteger currentTime = [array[0] intValue] * 60 + [array[1] intValue];

}


- (void)buttonClickStop

{

    _player.currentTime =0;//设值当前播放时间为0;

    

    [_playerstop]; // 停止播放

    [_playerplay];

}

// 循环播放

- (void)loopYesOrNo

{

    _player.numberOfLoops = -1;// 这里 正数就是播放几次 -1 就是无限循环

}

// 进度条

- (void)updateslider

{

    self.slider.value =self.player.currentTime;

    

    

}

- (void)sliderValueChanged

{

    [self.playerstop];

    

    [self.playersetCurrentTime:self.slider.value];

    

    [self.playerprepareToPlay];

    

    [self.playerplay];

    

}

//- (void)setProgress:(float)progress animated:(BOOL)animated

//{

//    //通过音频播放时长的百分比,progress进行赋值;(当前播放时间 /持续时间)

//   // _progress.progress = _player.currentTime / _player.duration;

//    

//    

//    animated = YES;

//}

// 音量大小

- (void)volumeChange

{

    _player.volume =_volumeSlider.value;

}

// 播放结束之后的动作 (代理实现)

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

{

    self.staus =playStatusNo;

    [_playerpause]; // 暂停播放;

    [NSTimerscheduledTimerWithTimeInterval:0.1target:selfselector:@selector(updateMusicTimeLabel)userInfo:selfrepeats:

    YES];

    [_buttonsetTitle:@"暂停播放"forState:UIControlStateNormal];


    

}

// 开始播放操作

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player

{

    [_playerplay];

}

// 声音开关

- (void)volumeOnOrOff:(UISwitch *)sender

{

   _player.volume = sender.on;

    

}



- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


这样整个播放器就创建成功了,界面不美观,只是为了实现以上的功能,有什么不足之处希望大家指点,探讨一起学习!