IOS關(guān)于音樂播放器

1.搭建音樂播放器的界面

對于這個音樂播放器我只實現(xiàn)了播放 ?暫停 ?下一曲 上一曲 停止 ?音量加減 和從歌曲列表中選歌并播放的功能 ?更多功能 歡迎大家參考我的代碼 ?進(jìn)行修改,代碼中有些不妥地方,還望各位大神指出。

整體界面搭建出來 ?是這個樣子:

這個是播放列表的樣子 ?我把它做成半透明的樣式;

在搭建界面的時候 ?我們可以使用XIB來畫 ? 這樣可以節(jié)約很多開發(fā)的時間 ?這個例子中 大多界面的地方我還是使用的純代碼實現(xiàn) ?因為純代碼編寫雖然有點耽誤時間 ? 但是將來進(jìn)行版本控制的時候 ?非常方便.在使用XIB的時候 ?要注意的問題:

當(dāng)你畫了一個控件 ?點擊右上角的輔助編輯器 ?你可以使用按住Ctrl ?加鼠標(biāo)左鍵 ? 拖到你的編輯器 ?然后為你的控件取名字. ? 當(dāng)你想刪除的時候 ?一定要點擊storyBord ?在你要刪除的空間的上面 右鍵 ?然后點擊叉叉 ? 就可以刪除與代碼區(qū)的綁定 ?。如果要再次綁定只需要再次Ctrl加鼠標(biāo)左鍵 ? 拖過來.

代碼區(qū):

#import "ViewController.h"#import#define WIDTH self.view.bounds.size.width#define HEIGHT self.view.bounds.size.height@interface ViewController (){

AVAudioPlayer *MyPlayer;//不能做成局部變量

NSTimer *timer;

NSMutableArray *songs;

NSUInteger myindex;

UIStepper *volumeStepper;

int index1;

UIView *view;

UITableView *myTableView;

NSMutableArray *dataArray;

}

@property (weak, nonatomic) IBOutlet UILabel *albumLabel;

@property (weak, nonatomic) IBOutlet UILabel *artistLabel;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;

@property (weak, nonatomic) IBOutlet UIProgressView *playProgressView;

@end

@implementation ViewController

-(void)dealloc{

if (timer) {

[timer invalidate];

timer = nil;

}

}

- (void)viewDidLoad {

[super viewDidLoad];

myindex = 1;

_playProgressView.progress = 0;

songs = [NSMutableArray arrayWithObjects:@"月半小夜曲",@"后會無期",@"靜靜看著你",@"李白",@"喜歡你",@"Taylor Swift - Love Story (International Radio Mi", nil];

_coverImageView.layer.cornerRadius = 100;

_coverImageView.clipsToBounds = YES;

NSString *filename = [[NSBundle mainBundle] pathForResource:@"李白" ofType:@"mp3"];

//拿到mp3

// NSString *filename = [[NSBundle mainBundle] pathForResource:@"后會無期" ofType:@"mp3"];

NSURL *fileUrl = [NSURL fileURLWithPath:filename];

//先拿到文件? 才能拿到數(shù)據(jù)? 才能刷新

[self updateUI:fileUrl];

MyPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];

//設(shè)置支持后臺播放后臺播放

//獲得當(dāng)前音頻會話對象的單例

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

[audioSession setActive:YES error:nil];

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

//打開項目? capabilities--->?? background modes--->? 打開audio and airplay? 設(shè)置支持后臺播放

//打開項目? capabilities--->?? background modes--->? 打開remote notifications 設(shè)置支持耳機(jī)

[[UIApplication sharedApplication]beginReceivingRemoteControlEvents];

//聲道

// player.pan = -1;

//音樂大小? 0~1?? 最大值可以修改? 是一種軟修改

//MyPlayer.volume = 1;

//文件播放速率? 用于快進(jìn) 快退

//player.enableRate = YES;

//player.rate = 4;

//跳過20s再播放

//MyPlayer.currentTime = 270;

MyPlayer.delegate = self;

//文件緩存

//[MyPlayer prepareToPlay];

//播放音樂

// [MyPlayer play];

//? ? progressSlider? = [[UISlider alloc]initWithFrame:CGRectMake(65, 440, 245, 15)];

//

//? ? [progressSlider addTarget:self action:@selector(progressValueChange) forControlEvents:UIControlEventValueChanged];

//? ? [self.view addSubview:progressSlider];

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(progressChange) userInfo:nil repeats:YES];

timer.fireDate = [NSDate distantFuture];

#if 0

volumeStepper = [[UIStepper alloc]initWithFrame:CGRectMake(WIDTH/3+15, 4*HEIGHT/7, 30, 20)];

[volumeStepper addTarget:self action:@selector(volumeChange:) forControlEvents:UIControlEventValueChanged];

volumeStepper.minimumValue = 0;

volumeStepper.maximumValue = 3;

volumeStepper.stepValue = 1;

//設(shè)置控制器背景圖片

volumeStepper.tintColor = [UIColor lightGrayColor];

[self.view addSubview:volumeStepper];

#endif

view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 300, 270)];

view.center = CGPointMake(WIDTH/2, HEIGHT/3);

view.hidden = YES;

view.alpha = 0.6;

[self.view addSubview:view];

myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height) style:UITableViewStylePlain];

[view addSubview:myTableView];

myTableView.dataSource = self;

myTableView.delegate = self;

[self loadDataModel];

}

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

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];

if (!cell) {

cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];

cell.backgroundColor = [UIColor colorWithRed:85.88 green:71.78 blue:60.74 alpha:0.6];

}

//cell.backgroundView = nil;

cell.contentView.backgroundColor = [UIColor colorWithRed:85.88 green:71.78 blue:60.74 alpha:0.6];

[myTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];

cell.opaque = NO;

cell.textLabel.backgroundColor = [UIColor colorWithRed:85.88 green:71.78 blue:60.74 alpha:0.6];

cell.textLabel.text = dataArray[indexPath.row];

return cell;

}

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

return dataArray.count;

}

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

NSString *filename = [[NSBundle mainBundle] pathForResource:songs[indexPath.row] ofType:@"mp3"];

NSURL *fileUrl = [NSURL fileURLWithPath:filename];

[self updateUI:fileUrl];

MyPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];

MyPlayer.volume = 1;

MyPlayer.delegate = self;

[MyPlayer prepareToPlay];

[MyPlayer play];

view.hidden = YES;

}

-(void)loadDataModel{

if (!dataArray) {

dataArray = [NSMutableArray array];

}

dataArray = [NSMutableArray arrayWithObjects:@"月半小夜曲",@"后會無期",@"靜靜看著你",@"李白",@"喜歡你",@"Taylor Swift - Love Story (International Radio Mi", nil];

}

-(void)volumeChange:(UIStepper *)sender{

MyPlayer.volume = sender.value;

}

//進(jìn)度條改變的回調(diào)方法

-(void)progressChange{

_playProgressView.progress = MyPlayer.currentTime/MyPlayer.duration;

[UIView animateWithDuration:8 animations:^{

_coverImageView.transform = CGAffineTransformRotate(_coverImageView.transform, M_PI_4/5);

}];

}

- (IBAction)volumeIncreaseButtonClicked:(UIButton *)sender {

MyPlayer.volume += 1;

if (MyPlayer.volume>4) {

MyPlayer.volume = 4;

}

}

- (IBAction)volumeDecreaseButtonClicked:(UIButton *)sender {

MyPlayer.volume -= 1;

if (MyPlayer.volume<0) {

MyPlayer.volume = 0;

}

}

//播放列表

- (IBAction)MusicListButtonClicked:(UIButton *)sender {

view.hidden = !view.hidden;

}

//播放結(jié)束

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

index1 = arc4random()%6;

if (index1!=myindex) {

myindex = index1;

}

NSString *filename = [[NSBundle mainBundle] pathForResource:songs[myindex] ofType:@"mp3"];

NSURL *fileUrl = [NSURL fileURLWithPath:filename];

[self updateUI:fileUrl];

MyPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];

MyPlayer.volume = 1;

MyPlayer.delegate = self;

[MyPlayer prepareToPlay];

[MyPlayer play];

}

//刷新界面 拿到歌的信息 刷新界面

-(void)updateUI:(NSURL *)fileUrl{

//代表和文件相關(guān)的數(shù)據(jù)

AVURLAsset *assset = [[AVURLAsset alloc]initWithURL:fileUrl options:nil];

//[assset availableMetadataFormats];//元數(shù)據(jù)的格式

NSArray *metaDataItems =[assset metadataForFormat:[[assset availableMetadataFormats] firstObject]];

for (AVMetadataItem *item in metaDataItems) {

if ([item.commonKey isEqualToString:@"artist"]) {

_artistLabel.text = [item.value description];

}

else if ([item.commonKey isEqualToString:@"title"]){

_titleLabel.text = [item.value description];

}

else if ([item.commonKey isEqualToString:@"albumName"]){

_albumLabel.text = [item.value description];

}

else if ([item.commonKey isEqualToString:@"artwork"]){

_coverImageView.image = [UIImage imageWithData:(id)item.value];

}

}

}

- (IBAction)buttonClicked:(UIButton *)sender {

if(MyPlayer.isPlaying){

timer.fireDate = [NSDate distantFuture];

[MyPlayer pause];

//[sender setTitle:@"播放" forState:UIControlStateNormal]? ;

}

else {

timer.fireDate = [NSDate distantPast];

[MyPlayer play];

//[sender setTitle:@"暫停" forState:UIControlStateNormal];

}

}

- (IBAction)prevButtonClicked:(UIButton *)sender {

timer.fireDate = [NSDate distantPast];

myindex --;

if (myindex==0) {

myindex = 5;

}

NSString *filename = [[NSBundle mainBundle] pathForResource:songs[myindex] ofType:@"mp3"];

NSURL *fileUrl = [NSURL fileURLWithPath:filename];

[self updateUI:fileUrl];

MyPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];

MyPlayer.volume = 1;

MyPlayer.delegate = self;

[MyPlayer prepareToPlay];

[MyPlayer play];

}

- (IBAction)nextButtonClicked:(UIButton *)sender {

timer.fireDate = [NSDate distantPast];

myindex++;

if (myindex>5) {

myindex = 0;

}

NSString *filename = [[NSBundle mainBundle] pathForResource:songs[myindex] ofType:@"mp3"];

NSURL *fileUrl = [NSURL fileURLWithPath:filename];

[self updateUI:fileUrl];

MyPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];

MyPlayer.volume = 1;

MyPlayer.delegate = self;

[MyPlayer prepareToPlay];

[MyPlayer play];

}

- (IBAction)stopButtonClicked:(UIButton *)sender {

timer.fireDate = [NSDate distantFuture];

[MyPlayer stop];

MyPlayer.currentTime = 0;

_playProgressView.progress = 0;

}

@end

文/hither(簡書作者)

原文鏈接:http://www.lxweimin.com/p/c59b29aaa500

著作權(quán)歸作者所有,轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),并標(biāo)注“簡書作者”。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容