片刻代码编写过程中音乐播放用到的代码,给大家作为参考
用到的PlayManager
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
typedef NS_ENUM(NSInteger, PlayModel){
PlayModelListCycle,
PlayModelSingleCycle,
PlayModelRandom,
PlayModelOrder
};
typedef NS_ENUM(NSInteger, PlayState){
PlayStatePause,
PlayStatePlay
};
@interface MusicPlayerManager : NSObject{
AVPlayer *_avPlayer;
AVPlayerItem *_avPlayerItem;
// NSInteger _musicIndex;
}
@property(nonatomic,retain) NSArray *musicUrlArray;
@property(nonatomic,assign) PlayModel playModel;
@property(nonatomic,assign,readonly) double progress;
@property(nonatomic,assign,readonly) double duration;
@property(nonatomic,assign,readonly) double availableDuration;
@property(readonly,assign,readonly) PlayState playState;
@property(nonatomic,assign) NSInteger musicIndex;
- (void)play;//播放
- (void)pause;//暂停
- (void)stop;//停止
- (void)nextMusic;//下一首
- (void)beforeMusic;//上一首
- (void)seekToTime:(double)newSeekTime;//根据时间跳转
- (void)changeMusicWithIndex:(NSInteger)index;//根据下标播放音乐
- (void)playFinsh;//播放完成
+ (instancetype)sharedMusicManage;//单例方法
@end
#import "MusicPlayerManager.h"
@implementation MusicPlayerManager
-(instancetype)init{
self=[super init];
if (self) {
//_playModel=PlayModelListCycle;
_avPlayer=[[AVPlayer alloc] init];
_musicUrlArray=[[NSArray alloc] init];
_musicIndex=0;
_playModel=PlayModelListCycle;
}
return self;
}
//单例方法
+ (instancetype)sharedMusicManage{
static MusicPlayerManager *manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[MusicPlayerManager alloc] init];
});
return manager;
}
-(void)setMusicUrlArray:(NSArray *)musicUrlArray{
if (_musicUrlArray!=musicUrlArray) {
[_musicUrlArray release];
_musicUrlArray=[musicUrlArray retain];
}
_avPlayerItem=[[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:_musicUrlArray[0]]];
[_avPlayer replaceCurrentItemWithPlayerItem:_avPlayerItem];
}
-(void)play{
[_avPlayer play];
}
-(void)pause{
[_avPlayer pause];
}
//下一首
- (void)nextMusic{
_musicIndex++;
if (_playModel == PlayModelRandom) {
_musicIndex = arc4random() % _musicUrlArray.count;
}
if (_musicIndex >= _musicUrlArray.count) {
_musicIndex = 0;
}
[self changeMusicWithIndex:_musicIndex];
}
//上一首
- (void)beforeMusic{
if (_playModel == PlayModelRandom) {
_musicIndex = arc4random() % _musicUrlArray.count;
}else{
_musicIndex--;
}
if (_musicIndex < 0) {
_musicIndex = _musicUrlArray.count - 1;
}
[self changeMusicWithIndex:_musicIndex];
}
//跳转到某个界面
- (void)seekToTime:(double)newSeekTime{
CMTime newTime = _avPlayer.currentTime;
newTime.value = newTime.timescale * newSeekTime;
[_avPlayer seekToTime:newTime];
}
//停止
- (void)stop{
[self seekToTime:0.0];
[_avPlayer pause];
}
//返回缓存时间
- (double)availableDuration{
NSArray *loadedTimeRanges = [[_avPlayer currentItem] loadedTimeRanges];
CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
float startSeconds = CMTimeGetSeconds(timeRange.start);
float durationSeconds = CMTimeGetSeconds(timeRange.duration);
NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
return result;
}
//播放完毕后的处理
- (void)playFinsh{
switch (_playModel) {
case PlayModelSingleCycle:
break;
case PlayModelRandom:
_musicIndex = arc4random() % [_musicUrlArray count];
break;
case PlayModelOrder:
{
[self pause];
return;
}
default:
_musicIndex++;
break;
}
[self changeMusicWithIndex:_musicIndex];
}
//根据数组下标播放音乐
- (void)changeMusicWithIndex:(NSInteger)index{
[self stop];
_avPlayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:_musicUrlArray[index]]];
[_avPlayer replaceCurrentItemWithPlayerItem:_avPlayerItem];
_musicIndex = index;
[_avPlayer play];
}
//返回播放状态
- (PlayState)playState{
if (_avPlayer.rate == 0.0) {
return PlayStatePause;
}
return PlayStatePlay;
}
//返回总时间
- (double)duration{
long long int duration = 1;
//检测到有歌曲时间以后再返回,负责分母为0会崩溃
if (_avPlayerItem.duration.timescale != 0) {
duration = _avPlayerItem.duration.value / _avPlayerItem.duration.timescale;
} else {
duration = 0;
}
return duration;
}
//返回当前播放时间
- (double)progress{
long long int currentTime = 0;
if (_avPlayerItem) {
currentTime = _avPlayerItem.currentTime.value / _avPlayerItem.currentTime.timescale;
}
return currentTime;
}
@end
用到的控制器基类
#import <UIKit/UIKit.h>
#import "RootRightViewController.h"
@interface MainListBaseViewController : UIViewController{
RootRightViewController *_rootRightVC;
UIView *_topView;
UILabel *_titleLabel;
}
@property(nonatomic,retain) UIView *topView;
@property(nonatomic,retain) UILabel *titleLabel;
@property(nonatomic,retain) UINavigationController *navigationC;
@property(nonatomic,retain) RootRightViewController *rootRightVC;
@property(nonatomic,retain) UIButton *button;
@end
#import "MainListBaseViewController.h"
#import "MacoHeader.h"
@interface MainListBaseViewController ()
@end
@implementation MainListBaseViewController
- (void)dealloc
{
[_rootRightVC release];
[_topView release];
[_titleLabel release];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.view addSubview:self.titleLabel];
//[self createChangeFrameButton];
[self createNaviBar];
}
-(UILabel *)titleLabel{
if (!_titleLabel) {
_titleLabel=[[UILabel alloc] initWithFrame:CGRectMake(50, 20, 60, 30)];
_titleLabel.backgroundColor=[UIColor whiteColor];
// _titleLabel.text=@"首页";
}
return _titleLabel;
}
-(void)createNaviBar{
self.topView=[[UIView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WITH, 30)];
//self.topView.backgroundColor=[UIColor yellowColor];
// self.titleLabel=[[UILabel alloc] initWithFrame:CGRectMake(60, 0, 40, 30)];
// self.titleLabel.text=@"首页";
// self.titleLabel.backgroundColor=[UIColor purpleColor];
_button=[UIButton buttonWithType:UIButtonTypeCustom];
_button.frame=CGRectMake(10, 0, 40, 30);
[_button setImage:[UIImage imageNamed:@"iconfont-liebiao"] forState:UIControlStateNormal];
[_button addTarget:self action:@selector(handleChangeFrameButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.topView addSubview:_button];
//[self.topView addSubview:self.titleLabel];
[self.view addSubview:self.topView];
}
-(void)createChangeFrameButton{
}
-(void)handleChangeFrameButtonAction:(UIButton *)button{
[self.rootRightVC changeViewFrame];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
接下来是主界面控制器继承自基类控制器
#import "BaseRadioDetailViewController.h"
@interface RadioPalyViewController : BaseRadioDetailViewController
@end
#import "RadioPalyViewController.h"
#import "MacoHeader.h"
#import "RequestManager.h"
#import <UIImageView+WebCache.h>
#import "MusicPlayerManager.h"
@interface RadioPalyViewController ()<RequestDelegate>
@property(nonatomic,retain) UIScrollView *scrollView;
@property(nonatomic,retain) UITableView *tableView;
@property(nonatomic,retain) UIView *playView;
@property(nonatomic,retain) NSDictionary *shareinfoDict;
@property(nonatomic,retain) MusicPlayerManager *playManager;
@end
@implementation RadioPalyViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor=[UIColor whiteColor];
// Do any additional setup after loading the view.
self.scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 52, SCREEN_WITH, SCREEN_HEIGHT-130)]; //scroll 显示大小
self.scrollView.contentSize=CGSizeMake(SCREEN_WITH*4, 0); //scroll内容的大小
self.scrollView.contentOffset = CGPointMake(SCREEN_WITH, 0);
self.scrollView.pagingEnabled = YES;
[self.view addSubview:self.scrollView];
[self.beforeButton addTarget:self action:@selector(pop:) forControlEvents:UIControlEventTouchUpInside];
[self tableView];
[self playView];
self.playManager=[MusicPlayerManager sharedMusicManage];
self.playManager.musicUrlArray=@[ @"http://fdfs.xmcdn.com/group4/M03/7E/69/wKgDs1PJ-fKx8yQtAEuOLNStMgk721.mp3",
@"http://fdfs.xmcdn.com/group4/M09/28/A9/wKgDs1QgAKnhwOCxAIn2i-ieFOo763.mp3",
@"http://fdfs.xmcdn.com/group6/M03/B9/56/wKgDhFUP6LjzFEwjAHZ_rwkSG7g294.mp3",
@"http://fdfs.xmcdn.com/group4/M06/93/4A/wKgDs1RRrtKTxnuLAFJrufqKR6k504.mp3",
@"http://fdfs.xmcdn.com/group6/M06/21/EB/wKgDg1TZkgrgnmmpAGwHr5T3Wnw284.mp3",
@"http://fdfs.xmcdn.com/group5/M04/A4/44/wKgDtVRz8v2SoyzoAFDCa7TS6uc267.mp3",
@"http://fdfs.xmcdn.com/group9/M01/09/86/wKgDZlVfA-6gcP3oAQYWDXqdG-4370.mp3"];
NSTimer *timer=[NSTimer timerWithTimeInterval:1 target:self selector:@selector(musicIsPlaying) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[self.playManager play];
[self.playButton addTarget:self action:@selector(handlePlayButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.backButton addTarget:self action:@selector(handleBackButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.nextButton addTarget:self action:@selector(handleNextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)handlePlayButtonAction:(UIButton *)button{
if (_playManager.playState==PlayStatePause) {
[_playManager play];
[self.playButton setImage:[UIImage imageNamed:@"iconfont-bofang"] forState:UIControlStateNormal];
}else{
[_playManager pause];
[self.playButton setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
}
}
-(void)handleNextButtonAction:(UIButton *)button{
[_playManager nextMusic];
NSLog(@"下一首");
NSLog(@"%li",_playManager.musicIndex);
}
-(void)handleBackButtonAction:(UIButton *)button{
[_playManager beforeMusic];
NSLog(@"上一首");
NSLog(@"%li",_playManager.musicIndex);
}
-(void)pop:(UIButton *)button{
[self.navigationController popViewControllerAnimated:YES];
}
-(UIView *)playView{
if (!_playView) {
_playView=[[UIView alloc] initWithFrame:CGRectMake(SCREEN_WITH, 52, SCREEN_WITH, 537)];
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(60, 30, 255, 255)];
imageView.backgroundColor=[UIColor blueColor];
// [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[self.shareinfoDict objectForKey:@"coverimg"]]]];
[imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://upload.pianke.me/old/newuploads/dd7276e1bea0552a57ea334da5aa846d.jpg"]]];
[_playView addSubview:imageView];
[self.scrollView addSubview:_playView];
}
return _playView;
}