音乐播放器(iOS完整复杂版)

来源:互联网 发布:linux查询arp 编辑:程序博客网 时间:2024/04/29 20:25

那么现在给同学补齐一个还算比较完整功能的音乐播放器,还有待完善!废话不多说,直接上代码!先看示例:







//

//  AppDelegate.h

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import <UIKit/UIKit.h>


typedef void (^remoteBlock)(UIEvent *event);

@interface AppDelegate :UIResponder <UIApplicationDelegate>


@property (strong,nonatomic) UIWindow *window;


/**

 *  一个回调远程事件的block

 */

@property (nonatomic,copy) remoteBlock removteBlock;


@end


//

//  AppDelegate.m

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import "AppDelegate.h"

#import <AVFoundation/AVFoundation.h>


@interface AppDelegate ()


@end


@implementation AppDelegate



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {


    // 设置音频会话类型

    AVAudioSession *session = [AVAudioSessionsharedInstance];

    [session setCategory:AVAudioSessionCategoryPlaybackerror:nil];

    [session setActive:YESerror:nil];

    

    // 接收远程事件

    [application beginReceivingRemoteControlEvents];

    

    returnYES;

}


/**

 *  锁屏按钮的远程通知

 */

- (void)remoteControlReceivedWithEvent:(UIEvent *)event

{

    if (event.type ==UIEventTypeRemoteControl) {

        if (self.removteBlock) {

            self.removteBlock(event);

        }

    }

}


- (void)applicationDidEnterBackground:(UIApplication *)application {

    // 开启后台任务

    [application beginBackgroundTaskWithExpirationHandler:nil];

}

@end


//

//  ZZMusic.h

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface ZZMusic : NSObject

@property (copy,nonatomic) NSString *name;

@property (copy,nonatomic) NSString *filename;

@property (copy,nonatomic) NSString *singer;

@property (copy,nonatomic) NSString *singerIcon;

@property (copy,nonatomic) NSString *icon;


@property (nonatomic,assign, getter = isPlaying)BOOL playing;

@end


//

//  ZZMusic.m

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import "ZZMusic.h"


@implementation ZZMusic


@end


//

//  UIImage+ZZ.h

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import <UIKit/UIKit.h>


@interface UIImage (ZZ)

+ (instancetype)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor;

@end


//

//  UIImage+ZZ.m

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import "UIImage+ZZ.h"


@implementation UIImage (ZZ)

+ (instancetype)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor

{

    // 1.加载原图

    UIImage *oldImage = [UIImageimageNamed:name];

    

    // 2.开启上下文

    CGFloat imageW = oldImage.size.width +2 * borderWidth;

    CGFloat imageH = oldImage.size.height +2 * borderWidth;

    CGSize imageSize =CGSizeMake(imageW, imageH);

    UIGraphicsBeginImageContextWithOptions(imageSize,NO, 0.0);

    

    // 3.取得当前的上下文

    CGContextRef ctx =UIGraphicsGetCurrentContext();

    

    // 4.画边框(大圆)

    [borderColor set];

    CGFloat bigRadius = imageW *0.5; //大圆半径

    CGFloat centerX = bigRadius;// 圆心

    CGFloat centerY = bigRadius;

    CGContextAddArc(ctx, centerX, centerY, bigRadius,0, M_PI *2, 0);

    CGContextFillPath(ctx);// 画圆

    

    // 5.小圆

    CGFloat smallRadius = bigRadius - borderWidth;

    CGContextAddArc(ctx, centerX, centerY, smallRadius,0, M_PI *2, 0);

    // 裁剪(后面画的东西才会受裁剪的影响)

    CGContextClip(ctx);

    

    // 6.画图

    [oldImage drawInRect:CGRectMake(borderWidth, borderWidth, oldImage.size.width, oldImage.size.height)];

    

    // 7.取图

    UIImage *newImage =UIGraphicsGetImageFromCurrentImageContext();

    

    // 8.结束上下文

    UIGraphicsEndImageContext();

    

    return newImage;

}


@end



//

//  NSString+ZZ.h

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/21.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface NSString (ZZ)

/**

 *  返回分与秒的字符串:01:60

 */

+ (NSString *)getMinuteSecondWithSecond:(NSTimeInterval)time;

@end



//

//  NSString+ZZ.m

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/21.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import "NSString+ZZ.h"


@implementation NSString (ZZ)


+ (NSString *)getMinuteSecondWithSecond:(NSTimeInterval)time {

    

    int minute = (int)time /60;

    int second = (int)time %60;

    

    if (second >9) { //2:10

        return [NSStringstringWithFormat:@"%d:%d",minute,second];

    }

    

    //2:09

    return [NSStringstringWithFormat:@"%d:0%d",minute,second];

}

@end


//

//  ZZAudioTool.h

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import <Foundation/Foundation.h>

#import <AVFoundation/AVFoundation.h>

@class ZZMusic;

@interface ZZAudioTool : NSObject

/**

 *  播放器

 */

@property(nonatomic,strong) AVAudioPlayer *player;


/*

 * 音乐播放前的准备工作

 */

- (void)prepareToPlayWithMusic:(ZZMusic *)music;


/*

 * 播放

 */

- (void)play;

/*

 * 暂停

 */

- (void)pause;


/**

 *  创建单例

 */

+ (instancetype)shareInstance;

/**

 *  播放音效

 *

 *  @param filename 音效文件名

 */

+ (void)playSound:(NSString *)filename;


/**

 *  销毁音效

 *

 *  @param filename 音效文件名

 */

+ (void)disposeSound:(NSString *)filename;


/**

 *  播放音乐

 *

 *  @param filename 音乐文件名

 */

+ (AVAudioPlayer *)playMusic:(NSString *)filename;


/**

 *  暂停音乐

 *

 *  @param filename 音乐文件名

 */

+ (void)pauseMusic:(NSString *)filename;


/**

 *  停止音乐

 *

 *  @param filename 音乐文件名

 */

+ (void)stopMusic:(NSString *)filename;


/**

 *  返回当前正在播放的音乐播放器

 */

+ (AVAudioPlayer *)currentPlayingAudioPlayer;


@end



//

//  ZZAudioTool.m

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import "ZZAudioTool.h"

#import "ZZMusic.h"

#import <MediaPlayer/MediaPlayer.h>


@implementation ZZAudioTool

/**

 *  存放所有的音频ID

 *  字典: filename作为key, soundID作为value

 */

static NSMutableDictionary *_soundIDDict;


/**

 *  存放所有的音乐播放器

 *  字典: filename作为key, audioPlayer作为value

 */

static NSMutableDictionary *_audioPlayerDict;


/**

 *  返回请求单例对象

 */

+ (instancetype)shareInstance

{

    staticZZAudioTool *audioTool;

    staticdispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        if (audioTool ==nil) {

            audioTool = [[ZZAudioToolalloc] init];

        }

    });

    return audioTool;

}


- (void)prepareToPlayWithMusic:(ZZMusic *)music

{

    if (!music.filename)return;

    

    // 创建播放器

    NSURL *musicURL = [[NSBundlemainBundle] URLForResource:music.filenamewithExtension:nil];

    self.player = [[AVAudioPlayeralloc] initWithContentsOfURL:musicURLerror:nil];

    

    // 准备

    [self.playerprepareToPlay];


    // 设置锁屏歌曲信息

    [selfsetUpLockInfoWithMP3Info:music];

}


- (void)setUpLockInfoWithMP3Info:(ZZMusic *)music

{

    NSLog(@"%s",__func__);

    //锁屏信息设置

    NSMutableDictionary *playingInfo = [NSMutableDictionarydictionary];

    

    //1.专辑名称

    playingInfo[MPMediaItemPropertyAlbumTitle] =@"中文十大金曲";

    

    //2.歌曲

    playingInfo[MPMediaItemPropertyTitle] = music.name;

    

    //3.歌手名称

    playingInfo[MPMediaItemPropertyTitle] = music.singer;

    

    //4.专辑图片

    if(music.icon){

        UIImage *artWorkImage = [UIImageimageNamed:music.icon];

        MPMediaItemArtwork *artwork = [[MPMediaItemArtworkalloc] initWithImage:artWorkImage];

        playingInfo[MPMediaItemPropertyArtwork] = artwork;

    }

    

    //5.锁屏音乐总时间

    playingInfo[MPMediaItemPropertyPlaybackDuration] =@(self.player.duration);

    

    //设置锁屏时的播放信息

    [MPNowPlayingInfoCenterdefaultCenter].nowPlayingInfo = playingInfo;

}


/*

 * 播放

 */

- (void)play

{

    [self.playerplay];

}


/*

 * 暂停

 */

- (void)pause

{

    [self.playerpause];

}


/**

 *  初始化

 */

+ (void)initialize

{

    _soundIDDict = [NSMutableDictionarydictionary];

    _audioPlayerDict = [NSMutableDictionarydictionary];

}


/**

 *  播放音效

 *

 *  @param filename 音效文件名

 */

+ (void)playSound:(NSString *)filename

{

    if (!filename)return;

    

    // 1.从字典中取出soundID

    SystemSoundID soundID = [_soundIDDict[filename]unsignedLongValue];

    if (!soundID) {// 创建

        // 加载音效文件

        NSURL *url = [[NSBundlemainBundle] URLForResource:filenamewithExtension:nil];

        

        if (!url)return;

        

        // 创建音效ID

        AudioServicesCreateSystemSoundID((__bridgeCFURLRef)url, &soundID);

        

        // 放入字典

        _soundIDDict[filename] =@(soundID);

    }

    

    // 2.播放

    AudioServicesPlaySystemSound(soundID);

}


/**

 *  销毁音效

 *

 *  @param filename 音效文件名

 */

+ (void)disposeSound:(NSString *)filename

{

    if (!filename)return;

    

    SystemSoundID soundID = [_soundIDDict[filename]unsignedLongValue];

    if (soundID) {

        // 销毁音效ID

        AudioServicesDisposeSystemSoundID(soundID);

        

        // 从字典中移除

        [_soundIDDictremoveObjectForKey:filename];

    }

}


/**

 *  播放音乐

 *

 *  @param filename 音乐文件名

 */

+ (AVAudioPlayer *)playMusic:(NSString *)filename

{

    if (!filename)return nil;

    

    // 1.从字典中取出audioPlayer

    AVAudioPlayer *audioPlayer =_audioPlayerDict[filename];

    if (!audioPlayer) {// 创建

        // 加载音乐文件

        NSURL *url = [[NSBundlemainBundle] URLForResource:filenamewithExtension:nil];

        

        if (!url)return nil;

        

        // 创建audioPlayer

        audioPlayer = [[AVAudioPlayeralloc] initWithContentsOfURL:urlerror:nil];

        

        // 缓冲

        [audioPlayer prepareToPlay];

        

        //        audioPlayer.enableRate = YES;

        //        audioPlayer.rate = 10.0;

        

        // 放入字典

        _audioPlayerDict[filename] = audioPlayer;

    }

    

    // 2.播放

    if (!audioPlayer.isPlaying) {

        [audioPlayer play];

    }

    

    return audioPlayer;

}


/**

 *  暂停音乐

 *

 *  @param filename 音乐文件名

 */

+ (void)pauseMusic:(NSString *)filename

{

    if (!filename)return;

    

    // 1.从字典中取出audioPlayer

    AVAudioPlayer *audioPlayer =_audioPlayerDict[filename];

    

    // 2.暂停

    if (audioPlayer.isPlaying) {

        [audioPlayer pause];

    }

}


/**

 *  停止音乐

 *

 *  @param filename 音乐文件名

 */

+ (void)stopMusic:(NSString *)filename

{

    if (!filename)return;

    

    // 1.从字典中取出audioPlayer

    AVAudioPlayer *audioPlayer =_audioPlayerDict[filename];

    

    // 2.暂停

    if (audioPlayer.isPlaying) {

        [audioPlayer stop];

        

        // 直接销毁

        [_audioPlayerDictremoveObjectForKey:filename];

    }

}


/**

 *  返回当前正在播放的音乐播放器

 */

+ (AVAudioPlayer *)currentPlayingAudioPlayer

{

    for (NSString *filenamein _audioPlayerDict) {

        AVAudioPlayer *audioPlayer =_audioPlayerDict[filename];

        

        if (audioPlayer.isPlaying) {

            return audioPlayer;

        }

    }

    

    returnnil;

}


@end



//

//  ZZMusicCell.h

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import <UIKit/UIKit.h>

@class ZZMusic;

@interface ZZMusicCell : UITableViewCell

+ (instancetype)cellWithTableView:(UITableView *)tableView;


@property (nonatomic,strong) ZZMusic *music;



@end


//

//  ZZMusicCell.m

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import "ZZMusicCell.h"

#import "ZZMusic.h"


@interface ZZMusicCell()


@end


@implementation ZZMusicCell


+ (instancetype)cellWithTableView:(UITableView *)tableView

{

    staticNSString *ID = @"music";

    ZZMusicCell *cell = [tableViewdequeueReusableCellWithIdentifier:ID];

    if (cell ==nil) {

        cell = [[ZZMusicCellalloc] initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:ID];

    }

    return cell;

}


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

    if (self = [superinitWithStyle:style reuseIdentifier:reuseIdentifier]) {

        self.backgroundColor = [UIColorclearColor];

        self.selectedBackgroundView = [[UIImageViewalloc] initWithImage:[UIImageimageNamed:@"backgroundImage"]];

    }

    

    returnself;

}


- (void)setMusic:(ZZMusic *)music

{

    _music = music;

    

    self.textLabel.text = music.name;

    self.detailTextLabel.text = music.singer;

    self.imageView.image = [UIImageimageNamed:music.singerIcon];

}


@end



//

//  ZZPlayerToolBar.h

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import <UIKit/UIKit.h>


typedef enum : NSUInteger {

    ZZPlayerToolBarPreviousButtonType,

    ZZPlayerToolBarNextButtonType,

    ZZPlayerToolBarPlayButtonType,

    ZZPlayerToolBarPauseButtonType,

    ZZPlayerToolBarTypeButtonType

} ZZPlayerToolBarButtonType;


@class ZZMusic,ZZPlayerToolBar;


@protocol ZZPlayerToolBarDelegate <NSObject>

@optional


- (void)playerToolBar:(ZZPlayerToolBar *)playerToolBar didClickBtnWithType:(ZZPlayerToolBarButtonType)type;


@end


@interface ZZPlayerToolBar : UIView


@property (nonatomic,strong) ZZMusic *music;


@property (nonatomic,assign) ZZPlayerToolBarButtonType type;


@property (nonatomic,weak) id <ZZPlayerToolBarDelegate> delegate;


+ (instancetype)playerToolBar;


@end



//

//  ZZPlayerToolBar.m

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import "ZZPlayerToolBar.h"

#import "ZZMusic.h"

#import "ZZAudioTool.h"

#import "NSString+ZZ.h"

#import "UIImage+ZZ.h"

#import "Colours.h"


@interface ZZPlayerToolBar()

@property (weak,nonatomic) UIImageView *bgImg;//背景图片

@property (weak,nonatomic) UIImageView *singerIcon;//歌手图片

@property (weak,nonatomic) UIButton *previousBtn;//上一首

@property (weak,nonatomic) UIButton *playBtn;//播放\暂停

@property (weak,nonatomic) UIButton *nextBtn;//下一首

@property (weak,nonatomic) UIButton *typeBtn;//播放模式

@property (weak,nonatomic) UISlider *timeSlider;//滚动条

@property (weak,nonatomic) UILabel *totalTimeLabel;//总时间

@property (weak,nonatomic) UILabel *currentTimeLabel;//当前播放的时间

@property (strong,nonatomic) CADisplayLink *link;//定时器

@property (assign,nonatomic, getter = isDragging)BOOL dragging;//是否正在拖拽


@end


@implementation ZZPlayerToolBar


- (CADisplayLink *)link {

    if (!_link) {

        _link = [CADisplayLinkdisplayLinkWithTarget:selfselector:@selector(update)];

    }

    return_link;

}


+ (instancetype)playerToolBar

{

    return [[selfalloc] init];

}


- (instancetype)initWithFrame:(CGRect)frame

{

    if (self = [superinitWithFrame:frame]) {

        [selfsetUpSubViews];

        

        [self.linkaddToRunLoop:[NSRunLoopmainRunLoop] forMode:NSDefaultRunLoopMode];


    }

    

    returnself;

}


- (instancetype)initWithCoder:(NSCoder *)decoder

{

    if (self = [superinitWithCoder:decoder]) {

        [selfsetUpSubViews];

        

        [self.linkaddToRunLoop:[NSRunLoopmainRunLoop] forMode:NSDefaultRunLoopMode];

    }

    

    returnself;

}


#pragma mark - setUp 初始化

- (void)setUpSubViews

{

    UIImageView *bgImg = [[UIImageViewalloc] init];

    bgImg.image = [UIImageimageNamed:@"play_bar_bg2"];

    [selfaddSubview:bgImg];

    self.bgImg = bgImg;

    

    UISlider *timeSlider = [[UISlideralloc] init];

    [timeSlider setThumbImage:[UIImageimageNamed:@"playbar_slider_thumb"]forState:UIControlStateNormal];

    [timeSlider addTarget:selfaction:@selector(timeSliderChange:)forControlEvents:UIControlEventValueChanged];

    [selfaddSubview:timeSlider];

    self.timeSlider = timeSlider;

    

    UILabel *currentTimeLabel = [[UILabelalloc] init];

    currentTimeLabel.font = [UIFontsystemFontOfSize:14.0f];

    currentTimeLabel.textColor = [UIColorwhiteColor];

    currentTimeLabel.textAlignment =NSTextAlignmentRight;

    currentTimeLabel.text =NSLocalizedString(@"00:00",nil);

    [selfaddSubview:currentTimeLabel];

    self.currentTimeLabel = currentTimeLabel;

    

    UILabel *totalTimeLabel = [[UILabelalloc] init];

    totalTimeLabel.font = [UIFontsystemFontOfSize:14.0f];

    totalTimeLabel.textColor = [UIColorlightGrayColor];

    totalTimeLabel.textAlignment =NSTextAlignmentLeft;

    totalTimeLabel.text =NSLocalizedString(@"00:00",nil);

    [selfaddSubview:totalTimeLabel];

    self.totalTimeLabel = totalTimeLabel;

    

    UIImageView *singerIcon = [[UIImageViewalloc] init];

    singerIcon.image = [UIImageimageNamed:@"zxy_icon.jpg"];

    [selfaddSubview:singerIcon];

    self.singerIcon = singerIcon;

    

    UIButton *previousBtn = [[UIButtonalloc] init];

    [previousBtn setImage:[UIImageimageNamed:@"playbar_prebtn_nomal"]forState:UIControlStateNormal];

    [previousBtn setImage:[UIImageimageNamed:@"playbar_prebtn_click"]forState:UIControlStateHighlighted];

    [previousBtn addTarget:selfaction:@selector(buttonClick:)forControlEvents:UIControlEventTouchUpInside];

    previousBtn.tag =ZZPlayerToolBarPreviousButtonType;

    [selfaddSubview:previousBtn];

    self.previousBtn = previousBtn;

    

    UIButton *playBtn = [[UIButtonalloc] init];

    [playBtn setImage:[UIImageimageNamed:@"playbar_playbtn_nomal"]forState:UIControlStateNormal];

    [playBtn setImage:[UIImageimageNamed:@"playbar_playbtn_click"]forState:UIControlStateHighlighted];

    [playBtn addTarget:selfaction:@selector(buttonClick:)forControlEvents:UIControlEventTouchUpInside];

    playBtn.tag =ZZPlayerToolBarPlayButtonType;

    [selfaddSubview:playBtn];

    self.playBtn = playBtn;

    

    UIButton *nextBtn = [[UIButtonalloc] init];

    [nextBtn setImage:[UIImageimageNamed:@"playbar_nextbtn_nomal"]forState:UIControlStateNormal];

    [nextBtn setImage:[UIImageimageNamed:@"playbar_nextbtn_click"]forState:UIControlStateHighlighted];

    [nextBtn addTarget:selfaction:@selector(buttonClick:)forControlEvents:UIControlEventTouchUpInside];

    nextBtn.tag =ZZPlayerToolBarNextButtonType;

    [selfaddSubview:nextBtn];

    self.nextBtn = nextBtn;

    

    UIButton *typeBtn = [[UIButtonalloc] init];

    typeBtn.layer.borderWidth =1;

    typeBtn.layer.borderColor = [UIColorblueColor].CGColor;

    [typeBtn addTarget:selfaction:@selector(buttonClick:)forControlEvents:UIControlEventTouchUpInside];

    typeBtn.tag =ZZPlayerToolBarTypeButtonType;

#warning - 没图先隐藏

    typeBtn.hidden =YES;

    [selfaddSubview:typeBtn];

    self.typeBtn = typeBtn;

}


- (void)update

{

    // 1.更新进度条

    double currentTime = [ZZAudioToolshareInstance].player.currentTime;

    self.timeSlider.value = currentTime;

    

    // 2.更新时间

    self.currentTimeLabel.text = [NSStringgetMinuteSecondWithSecond:currentTime];

}


/**

 *  时间滑动变化

 */

- (void)timeSliderChange:(UISlider *)slider

{

    // 1.播放器进度

    [ZZAudioToolshareInstance].player.currentTime = slider.value;

    

    // 2.工具条的当前时间

    self.currentTimeLabel.text = [NSStringgetMinuteSecondWithSecond:slider.value];

}


/**

 *  点击按钮

 *

 *  @param button 根据按钮类型来判断

 */

- (void)buttonClick:(UIButton *)button

{

    if ([self.delegaterespondsToSelector:@selector(playerToolBar:didClickBtnWithType:)]) {

        if (button.tag ==ZZPlayerToolBarPlayButtonType) {

            if (self.music.playing) { // 播放

                self.music.playing =NO;

                [button setImage:[UIImageimageNamed:@"playbar_pausebtn_nomal"]forState:UIControlStateNormal];

                [button setImage:[UIImageimageNamed:@"playbar_pausebtn_click"]forState:UIControlStateHighlighted];

                button.tag =ZZPlayerToolBarPauseButtonType;

                [self.delegateplayerToolBar:selfdidClickBtnWithType:button.tag];


            }

        } elseif (button.tag ==ZZPlayerToolBarPauseButtonType) {// 暂停

            self.music.playing =YES;

            [button setImage:[UIImageimageNamed:@"playbar_playbtn_nomal"]forState:UIControlStateNormal];

            [button setImage:[UIImageimageNamed:@"playbar_playbtn_click"]forState:UIControlStateHighlighted];

            button.tag =ZZPlayerToolBarPlayButtonType;

            [self.delegateplayerToolBar:selfdidClickBtnWithType:button.tag];

            

        } elseif (button.tag ==ZZPlayerToolBarNextButtonType | button.tag ==ZZPlayerToolBarPreviousButtonType) {

            [self.playBtnsetImage:[UIImageimageNamed:@"playbar_playbtn_nomal"]forState:UIControlStateNormal];

            [self.playBtnsetImage:[UIImageimageNamed:@"playbar_playbtn_click"]forState:UIControlStateHighlighted];

            [self.delegateplayerToolBar:selfdidClickBtnWithType:button.tag];


        } else {

            [self.delegateplayerToolBar:selfdidClickBtnWithType:button.tag];

        }

    }

}


/**

 *  拿到真实的尺寸进行子控件的布局

 */

- (void)layoutSubviews

{

#warning - 一定要调用super的方法

    [superlayoutSubviews];

    

    CGFloat margin =5;

    

    self.bgImg.frame =self.frame;

    

    CGFloat currentTimeLabelX =10;

    CGFloat currentTimeLabelY =5;

    CGFloat currentTimeLabelW =40;

    CGFloat currentTimeLabelH =30;

    self.currentTimeLabel.frame =CGRectMake(currentTimeLabelX, currentTimeLabelY, currentTimeLabelW, currentTimeLabelH);

    

    CGFloat timeSliderX =CGRectGetMaxX(self.currentTimeLabel.frame) + margin;

    CGFloat timeSliderY = currentTimeLabelY;

    CGFloat timeSliderW =self.frame.size.width -2 * (currentTimeLabelW + currentTimeLabelX + margin);

    CGFloat timeSliderH = currentTimeLabelH;

    self.timeSlider.frame =CGRectMake(timeSliderX, timeSliderY, timeSliderW, timeSliderH);

    

    CGFloat totalTimeLabelX =self.frame.size.width - currentTimeLabelW - currentTimeLabelX;

    CGFloat totalTimeLabelY = currentTimeLabelY;

    CGFloat totalTimeLabelW = currentTimeLabelW;

    CGFloat totalTimeLabelH = currentTimeLabelH;

    self.totalTimeLabel.frame =CGRectMake(totalTimeLabelX, totalTimeLabelY, totalTimeLabelW, totalTimeLabelH);

    

    CGFloat singerIconX = currentTimeLabelX;

    CGFloat singerIconY =CGRectGetMaxY(self.timeSlider.frame) + margin;

    CGFloat singerIconW =50;

    CGFloat singerIconH = singerIconW;

    self.singerIcon.frame =CGRectMake(singerIconX, singerIconY, singerIconW, singerIconH);

    

    CGFloat previousBtnX =CGRectGetMaxX(self.singerIcon.frame) + 25;

    CGFloat previousBtnY = singerIconY;

    CGFloat previousBtnW =50;

    CGFloat previousBtnH = previousBtnW;

    self.previousBtn.frame =CGRectMake(previousBtnX, previousBtnY, previousBtnW, previousBtnH);

    

    CGFloat playBtnX =CGRectGetMaxX(self.previousBtn.frame) + 25;

    CGFloat playBtnY = singerIconY -5;

    CGFloat playBtnW =60;

    CGFloat playBtnH = playBtnW;

    self.playBtn.frame =CGRectMake(playBtnX, playBtnY, playBtnW, playBtnH);

    

    CGFloat nextBtnX =CGRectGetMaxX(self.playBtn.frame) + 25;

    CGFloat nextBtnY = singerIconY;

    CGFloat nextBtnW = previousBtnW;

    CGFloat nextBtnH = previousBtnW;

    self.nextBtn.frame =CGRectMake(nextBtnX, nextBtnY, nextBtnW, nextBtnH);

    

    CGFloat typeBtnX =CGRectGetMaxX(self.nextBtn.frame) + 20;

    CGFloat typeBtnY = singerIconY;

    CGFloat typeBtnW = previousBtnW;

    CGFloat typeBtnH = previousBtnW;

    self.typeBtn.frame =CGRectMake(typeBtnX, typeBtnY, typeBtnW, typeBtnH);

}


#pragma mark - setter 赋值&mvc思想

- (void)setMusic:(ZZMusic *)music

{

    _music = music;

    

    // 设置歌手图片数据

    [selfsetUpSingerIconData];

    

    // 设置滑动条的数据

    [selfsetUpSliderData];

}


/**

 *  设置歌手图片数据

 */

- (void)setUpSingerIconData

{

    // 0.设置圆角

    self.singerIcon.image = [UIImagecircleImageWithName:self.music.singerIconborderWidth:2borderColor:[UIColorskyBlueColor]];

    

#warning - 后期再补图片旋转

//    // 1.单位矩阵

//    self.singerIcon.transform = CGAffineTransformIdentity;

}


/**

 *  设置滑动条的数据

 */

- (void)setUpSliderData

{

    // 0.去除当前播放歌曲的总时间

    double duration = [ZZAudioToolshareInstance].player.duration;

    

    // 1.将时间转换&设置时间属性

    self.totalTimeLabel.text = [NSStringgetMinuteSecondWithSecond:duration];

    

    // 2.设置slider的最大值

    self.timeSlider.maximumValue = duration;

    

    // 3.重置slider的播放时间

    self.timeSlider.value =0;

}


- (void)dealloc

{

    //移除定时器

    [self.linkremoveFromRunLoop:[NSRunLoopmainRunLoop] forMode:NSDefaultRunLoopMode];

}


@end



//

//  ZZMusicsController.h

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import <UIKit/UIKit.h>


@interface ZZMusicsController :UIViewController


@end



//

//  ZZMusicsController.m

//  05-音乐播放器

//

//  Created by 周昭 on 2017/3/20.

//  Copyright © 2017 ZZ. All rights reserved.

//


#import "ZZMusicsController.h"

#import "ZZMusic.h"

#import "ZZMusicCell.h"

#import "ZZAudioTool.h"

#import "MJExtension.h"

#import "ZZPlayerToolBar.h"

#import "NSString+ZZ.h"

#import "AppDelegate.h"

#import <AVFoundation/AVFoundation.h>


@interface ZZMusicsController ()<UITableViewDelegate,UITableViewDataSource,AVAudioPlayerDelegate,ZZPlayerToolBarDelegate>

@property (nonatomic,strong) NSArray *musics;

@property (nonatomic,strong) AVAudioPlayer *currentPlayingAudioPlayer;

@property (nonatomic,weak) UITableView *tableView;

@property (nonatomic,weak) UIImageView *imgView;

@property (nonatomic,weak) ZZPlayerToolBar *playToolBar;

/**

 *  当前播放的索引

 */

@property (nonatomic,assign) NSInteger musicIndex;

@end


@implementation ZZMusicsController


#pragma mark - 懒加载

- (NSArray *)musics

{

    if (!_musics) {

        self.musics = [ZZMusicobjectArrayWithFilename:@"Musics.plist"];

    }

    return_musics;

}


- (void)viewDidLoad {

    [superviewDidLoad];

    

    // 0.设置标题&背景

    [selfsetUpTitle];

    

    // 1.初始化tableView

    [selfsetUpTableView];

    

    // 2.初始化playerToolBar

    [selfsetUpPlayerToolBar];

    

    // 3.随机播放

    [selfselectIndexPathWithRow:self.musicIndex];

    

    // 4.接收远程事件

    [selfsetUpRemovteEvent];

}


#pragma mark - setUp 初始化

- (void)setUpRemovteEvent

{

    ((AppDelegate *)[UIApplicationsharedApplication].delegate).removteBlock = ^(UIEvent *event) {

        switch (event.subtype) {

            caseUIEventSubtypeRemoteControlNextTrack:

                [selfplayNextMusic];

                break;

            caseUIEventSubtypeRemoteControlPreviousTrack:

                [selfplayPreviousMusic];

                break;

            caseUIEventSubtypeRemoteControlPause:

                [selfpauseCurrentMusic];

                break;

            caseUIEventSubtypeRemoteControlPlay:

                [selfplayCurrentMusic];

                break;

        }

    };

}


- (void)setUpPlayerToolBar

{

    ZZPlayerToolBar *playToolBar = [ZZPlayerToolBarplayerToolBar];

    playToolBar.frame =CGRectMake(0,self.view.frame.size.height - 95, self.view.frame.size.width,95);

    playToolBar.delegate =self;

    [self.viewaddSubview:playToolBar];

    self.playToolBar = playToolBar;

}


- (void)setUpTableView

{

    // 0.创建tableView

    UITableView *tableView = [[UITableViewalloc] init];

    tableView.delegate =self;

    tableView.dataSource =self;

    tableView.tableFooterView = [[UIViewalloc] init];

    

    // 1.设置背景

    UIImageView *imgView = [[UIImageViewalloc] init];

    imgView.frame =self.view.frame;

    imgView.image = [UIImageimageNamed:@"backgroundImage"];

    tableView.backgroundView = imgView;

    

    tableView.frame =CGRectMake(0,0, self.view.frame.size.width,self.view.frame.size.height);

    [self.viewaddSubview:tableView];

    self.tableView = tableView;

}


- (void)setUpTitle

{

    // 0.设置标题

    self.title =NSLocalizedString(@"音乐播放器",nil);

}


#pragma mark - ZZPlayerToolBarDelegate

- (void)playerToolBar:(ZZPlayerToolBar *)playerToolBar didClickBtnWithType:(ZZPlayerToolBarButtonType)type

{

    switch (type) {

        caseZZPlayerToolBarPreviousButtonType:

            [selfplayPreviousMusic];

            break;

            

        caseZZPlayerToolBarNextButtonType:

            [selfplayNextMusic];

            break;

            

        caseZZPlayerToolBarPlayButtonType:

            [selfplayCurrentMusic];

            break;

            

        caseZZPlayerToolBarPauseButtonType:

            [selfpauseCurrentMusic];

            break;

            

        caseZZPlayerToolBarTypeButtonType:

            [selfplayStyleMusic];

            break;

            

        default:

            break;

    }

}


/**

 *  播放上一首

 */

- (void)playPreviousMusic

{

    if (self.musicIndex ==0) { //第一首则回到最后一首

        self.musicIndex =self.musics.count -1;

    } else {

        self.musicIndex--;

    }

    

    [selfselectIndexPathWithRow:self.musicIndex];

}


/**

 *  播放下一首

 */

- (void)playNextMusic

{

    if (self.musicIndex ==self.musics.count -1) { //最后一首

        self.musicIndex =0;

    } else {

        self.musicIndex++;

    }

    

    [selfselectIndexPathWithRow:self.musicIndex];

}


/**

 *  播放

 */

- (void)playCurrentMusic

{

    [[ZZAudioToolshareInstance] play];

}


/**

 *  暂停

 */

- (void)pauseCurrentMusic

{

    [[ZZAudioToolshareInstance] pause];

}


/**

 *  更换播放模式

 */

- (void)playStyleMusic

{

    

}


- (void)selectIndexPathWithRow:(NSInteger)row

{

    // 0.取得当前选中

    NSIndexPath *selectedPath = [self.tableViewindexPathForSelectedRow];


    // 1.主动选中下一行

    NSIndexPath *currentPath = [NSIndexPathindexPathForRow:row inSection:selectedPath.section];

    [self.tableViewselectRowAtIndexPath:currentPathanimated:YESscrollPosition:UITableViewScrollPositionTop];

    [selftableView:self.tableViewdidSelectRowAtIndexPath:currentPath];

    

    // 2.播放音乐

    [selfplayMusic];

}


/**

 *  播放音乐

 */

- (void)playMusic

{

    // 0.取出播放的歌曲

    ZZMusic *music =self.musics[self.musicIndex];

    music.playing =YES;


    // 1.初始化播放器

    [[ZZAudioToolshareInstance] prepareToPlayWithMusic:music];

    

    // 2.设置代理

    [ZZAudioToolshareInstance].player.delegate =self;

    

    // 3.更改播放工具条数据

    self.playToolBar.music =self.musics[self.musicIndex];

    

    // 4.播放

    [[ZZAudioToolshareInstance] play];

}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    returnself.musics.count;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    // 1.创建cell

    ZZMusicCell *cell = [ZZMusicCellcellWithTableView:tableView];

    

    // 2.设置cell的数据

    cell.music =self.musics[indexPath.row];

    

    return cell;

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return70;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    // 0.取出要播放的音乐

    ZZMusic *music =self.musics[indexPath.row];

    if (music.playing ==YES) return;

    music.playing =YES;

    

    // 1.取得索引值

    self.musicIndex = indexPath.row;

    

    // 2.播放音乐

    [selfplayMusic];

}


- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

{

    // 0.停止音乐直接释放

    ZZMusic *music =self.musics[indexPath.row];

    music.playing =NO;

    [ZZAudioToolstopMusic:music.filename];

}


#pragma mark - AVAudioPlayerDelegate

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

{

    if (!flag ==YES) return;

    

    [selfplayNextMusic];

}


@end



0 0
原创粉丝点击