音乐播放器(OC)

这里写图片描述

我添加的是这几首歌曲

这里写图片描述

1.主界面和歌曲列表都是拖控件的

2.ViewController里的代码

#import "ViewController.h"
#import "MusicList_ViewController.h"
//导入音频播放器框架
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()<AVAudioPlayerDelegate>
//歌曲名字
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
//歌曲时间
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
//歌曲总时间
@property (weak, nonatomic) IBOutlet UILabel *timeLabel2;
//调节音量
@property (weak, nonatomic) IBOutlet UISlider *volumeSlider;
//歌曲进度
@property (weak, nonatomic) IBOutlet UISlider *processSlider;
//播放暂停按钮
@property (weak, nonatomic) IBOutlet UIButton *transmitBTN;
//播放顺序
@property (weak, nonatomic) IBOutlet UIButton *PlaytheorderAction;
//背景
@property (weak, nonatomic) IBOutlet UIImageView *Setting;
//旋转图片
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
//旋转图片(小)
@property (weak, nonatomic) IBOutlet UIImageView *imageView2;

//声明音频播放器对象的属性,便于以下代码操作
@property (retain)AVAudioPlayer* player;

//音乐的名字
@property (retain)NSString* musicName;

//判断当前是播放还是暂停
@property (assign)BOOL isBool;

//记录播放歌曲的下标
@property (assign)NSInteger number;
//数据源
@property (retain)NSMutableArray* dataSource;
//用来播放顺序
@property (assign)NSInteger Musicorder;
//用来改变皮肤
@property (assign)NSInteger backInt;
//图片转动
@property (assign)double Turn;

//存歌手图片
@property (retain)NSArray* SingerpicturesArr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

//    self.title = @"LGG音乐播放器";

    [_volumeSlider setThumbImage:[UIImage imageNamed:@"TB"] forState:UIControlStateNormal];

    [_processSlider setThumbImage:[UIImage imageNamed:@"TB"] forState:UIControlStateNormal];

    //获取文件的相对路径
    NSString* path1 = [[NSBundle mainBundle]pathForResource:@"Song information" ofType:@"plist"];
    //读取plist文件的内容
    NSArray* arr = [NSArray arrayWithContentsOfFile:path1];
    //以不可变得数组变成可变数组
    _dataSource = [NSMutableArray arrayWithArray:arr];

    //获取音频文件的相对路径
    NSString* path = [[NSBundle mainBundle]pathForResource:@"石进 - 夜的钢琴曲四" ofType:@"mp3"];
    //把相对路径转成url
    NSURL* url = [NSURL fileURLWithPath:path];
    //初始化音乐播放器
    _player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];

    //设置代理
    _player.delegate = self;

    //加载到内存准备播放
    [_player prepareToPlay];

    //初始化播放顺序,让它开始就是随机播放
    _Musicorder = 0;

    //监听通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeMusic:) name:@"music" object:nil];

    //监听通知(把点击要播放的下标获取到传到首页)
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(subscriptMusic:) name:@"subscript" object:nil];

    //光盘转动时间函数
    NSTimer* timer2 = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(TurnthePicture) userInfo:nil repeats:YES];

    _SingerpicturesArr = @[@"1_1",@"2_2",@"3_3",@"4_4",@"5_5",@"6_6",@"7_7"];
    //圆角
    _imageView2.layer.cornerRadius = _imageView2.frame.size.width/2;
    //将多余的部分切掉
    _imageView2.layer.masksToBounds = YES;
}

-(void)changeMusic:(NSNotification*)notication
{
    _musicName = notication.object;
    NSLog(@"notication ===== %@",notication.object);

    [self playMusic];
}

-(void)subscriptMusic:(NSNotification*)notication
{
    _number = [notication.object integerValue];
    NSLog(@"notication.object ==== %@", notication.object);
    NSLog(@"_number ==== %ld", (long)_number);

    //歌手图片(歌曲列表中点击更改图片)
    _imageView2.image = [UIImage imageNamed:_SingerpicturesArr[_number]];
}

//播放顺序
- (IBAction)shuffleplayAction:(UIButton *)sender {
    NSLog(@"播放顺序");
    NSArray* arr = @[@"player_btn_repeat_normal",@"player_btn_repeatone_normal",@"player_btn_random_normal"];

    if (_Musicorder != 2) {
        _Musicorder++;
    }else{
        _Musicorder = 0;
    }
    //更换按钮图片
    [_PlaytheorderAction setImage:[UIImage imageNamed:arr[_Musicorder]] forState:UIControlStateNormal];
}

//上一首
- (IBAction)OnaAction:(UIButton *)sender {
    NSLog(@"上一首");
    if (_Musicorder == 2) {
        NSLog(@"随机播放===================");
        NSInteger RandomPlay = arc4random()%_dataSource.count;
        NSLog(@"RandomPlay === %ld", (long)RandomPlay);
        if (_number != RandomPlay) {
            _number = RandomPlay;
        }else{
            _number = arc4random()%_dataSource.count;
        }
        _musicName = _dataSource[_number];
        //歌手图片
        _imageView2.image = [UIImage imageNamed:_SingerpicturesArr[_number]];
    }else{
        if (_number != 0) {
            _number--;
        }else{
            _number = _dataSource.count-1;
        }
        _musicName = _dataSource[_number];
        //歌手图片
        _imageView2.image = [UIImage imageNamed:_SingerpicturesArr[_number]];
    }
    [self playMusic];
}

//播放音乐
- (IBAction)playmusicAction:(UIButton *)sender {
    _isBool =! _isBool;
    if (_isBool) {
//        NSLog(@"播放音乐");
        [_player play];
        NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateUI) userInfo:nil repeats:YES];
        [_transmitBTN setImage:[UIImage imageNamed:@"hp_player_btn_pause_normal"] forState:UIControlStateNormal];
    }else{
//        NSLog(@"暂停音乐");
        [_player stop];
        [_transmitBTN setImage:[UIImage imageNamed:@"hp_player_btn_play_normal"] forState:UIControlStateNormal];
    }
}

//下一首
- (IBAction)ThefollowingpieceAction:(UIButton *)sender {
    NSLog(@"下一首");
    if (_Musicorder == 2) {
        NSLog(@"随机播放===================");
        NSInteger RandomPlay = arc4random()%_dataSource.count;
        NSLog(@"RandomPlay === %ld", (long)RandomPlay);
        if (_number != RandomPlay) {
            _number = RandomPlay;
        }else{
            _number = arc4random()%_dataSource.count;
        }
        _musicName = _dataSource[_number];
        //歌手图片
        _imageView2.image = [UIImage imageNamed:_SingerpicturesArr[_number]];
    }else{
        if (_number != _dataSource.count-1) {
            _number++;
        }else{
            _number = 0;
        }
        _musicName = _dataSource[_number];
        //歌手图片
        _imageView2.image = [UIImage imageNamed:_SingerpicturesArr[_number]];
    }
    [self playMusic];
}

//图片转动
-(void)TurnthePicture
{
    if (_isBool)
    {
        _Turn=_Turn+0.01;
        if (_Turn>6.28) {
            _Turn=0;
        }
        _imageView.transform=CGAffineTransformMakeRotation(_Turn);
        _imageView2.transform=CGAffineTransformMakeRotation(_Turn);
    }
}

//歌曲列表
- (IBAction)ThesonglistAction:(UIButton *)sender {
//    NSLog(@"歌曲列表");
    MusicList_ViewController* musiclistVC = [[MusicList_ViewController alloc]init];
    [self presentViewController:musiclistVC animated:YES completion:nil];
}

//歌曲声音大小调节
- (IBAction)volumeAction:(UISlider *)sender {
//    NSLog(@"歌曲声音大小调节");
    [_player setVolume:sender.value*100];
}

//歌曲进度
- (IBAction)processAction:(UISlider *)sender {
//    NSLog(@"歌曲进度-------1");
    //根据Slider的值直接改变进度,这样会出现卡顿的噪音
    //_player.currentTime = sender.value*_player.duration;
    [_player stop];
    _player.currentTime = sender.value*_player.duration;
}
- (IBAction)touchLeaveAcyion:(UISlider *)sender {
    _isBool =! _isBool;
    [self playmusicAction:nil];
}

-(void)updateUI
{
    //_player.duration //总时长
    //_player.currentTime //播放了的时长
    _processSlider.value = _player.currentTime/_player.duration;

    NSInteger allmm = _player.duration/60;
    NSInteger allss = (NSInteger)_player.duration%60;

    NSInteger cuMM = _player.currentTime/60;
    NSInteger cuSS = (NSInteger)_player.currentTime%60;

    _timeLabel.text = [NSString stringWithFormat:@"%.2ld:%.2ld", (long)cuMM, (long)cuSS];
    _timeLabel2.text = [NSString stringWithFormat:@"%.2ld:%.2ld", (long)allmm, (long)allss];
}

-(void)playMusic
{

    _nameLabel.text = _musicName;
    //获取音频文件的相对路径
    NSString* path = [[NSBundle mainBundle]pathForResource:_musicName ofType:@"mp3"];
    //把相对路径转成url
    NSURL* url = [NSURL fileURLWithPath:path];
    if (_player) {
        _player = nil;
    }
    //初始化音乐播放器
    _player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];

    //设置代理
    _player.delegate = self;

    //加载到内存准备播放
    [_player prepareToPlay];
    _isBool = NO;
    //播放
    [self playmusicAction:nil];
    if (_player.play) {
        [_transmitBTN setImage:[UIImage imageNamed:@"hp_player_btn_pause_normal"] forState:UIControlStateNormal];
    }
}

//播放完某首歌回调
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"播放完成");
    if (_Musicorder == 0) {
        NSLog(@"循环播放");
        [self ThefollowingpieceAction:nil];
    }else if(_Musicorder == 1){
        NSLog(@"单曲循环");
        //单曲循环后为开,让它单曲循环后能直接播放
        _isBool = NO;
        //播放
        [self playmusicAction:nil];
    }else if(_Musicorder == 2){
        NSLog(@"随机播放===================");
        NSInteger RandomPlay = arc4random()%_dataSource.count;
        NSLog(@"RandomPlay === %ld", (long)RandomPlay);
        if (_number != RandomPlay) {
            _number = RandomPlay;
        }else{
            _number = arc4random()%_dataSource.count;
        }
        _musicName = _dataSource[_number];
        //歌手图片
        _imageView2.image = [UIImage imageNamed:_SingerpicturesArr[_number]];
        [self playMusic];
    }
}

//皮肤
- (IBAction)TheSkinAction:(UIButton *)sender {
    NSLog(@"pihu");
    NSArray* settingArr = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10"];
    if (_backInt != settingArr.count-1) {
        _backInt++;
    }else{
        _backInt = 0;
    }
    _Setting.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", settingArr[_backInt]]];
}

//音乐播放中断
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
    NSLog(@"音乐被突然中断,比如系统来电话了");
}

//中断以结束
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags
{
    NSLog(@"中断以结束,可以正常播放音乐了");
    [self playmusicAction:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

3.MusicList_ViewController(歌曲列表)里的代码

#import "MusicList_ViewController.h"
#import "ViewController.h"

@interface MusicList_ViewController ()<UITableViewDelegate,UITableViewDataSource>
//表格视图
@property (weak, nonatomic) IBOutlet UITableView *tableView;


//数据源
@property (retain)NSMutableArray* dataSource;

@end

@implementation MusicList_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //获取文件的相对路径
    NSString* path = [[NSBundle mainBundle]pathForResource:@"Song information" ofType:@"plist"];
    //读取plist文件的内容
    NSArray* arr = [NSArray arrayWithContentsOfFile:path];
    //以不可变得数组变成可变数组
    _dataSource = [NSMutableArray arrayWithArray:arr];

    UIImageView *backImageView=[[UIImageView alloc]initWithFrame:self.view.bounds];
    [backImageView setImage:[UIImage imageNamed:@"2"]];
    _tableView.backgroundView = backImageView;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellID = @"cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    //设置单元格的标题
    cell.textLabel.text = _dataSource[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
//可以监听到当前用户点击的是哪一行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消选中行
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    //模态回退
    [self dismissViewControllerAnimated:YES completion:nil];

    //通知
    [[NSNotificationCenter defaultCenter]postNotificationName:@"music" object:_dataSource[indexPath.row]];
    //通知(把点击要播放的下标获取到传到首页)
    [[NSNotificationCenter defaultCenter]postNotificationName:@"subscript" object:[NSString stringWithFormat:@"%ld", (long)indexPath.row]];
}

//返回每个区的的头部视图高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    //默认高度
    return 44;
}

//返回每个区的的尾部视图高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    //默认高度
    return 44;
}

//返回自定义的头部视图,这个方法里自定义视图的高度是多少那返回区头部视图的高度的方法就应该返回多少,两者要统一
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, tableView.frame.size.width, 44)];
    label.text = @"--歌曲列表--";
    //居中
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    return label;
}

//返回自定义的尾部视图,这个方法里自定义视图的高度是多少那返回区尾部视图的高度的方法就应该返回多少,两者要统一
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, tableView.frame.size.width, 44);
    btn.backgroundColor = [UIColor clearColor];
    [btn setTitle:@"返回" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    return btn;
}

-(void)btnAction:(UIButton*)sender
{
    //模态回退
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值