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

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

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

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

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

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

當(dāng)你畫了一個控件 ?點(diǎn)擊右上角的輔助編輯器 ?你可以使用按住Ctrl ?加鼠標(biāo)左鍵 ? 拖到你的編輯器 ?然后為你的控件取名字. ? 當(dāng)你想刪除的時候 ?一定要點(diǎn)擊storyBord ?在你要刪除的空間的上面 右鍵 ?然后點(diǎn)擊叉叉 ? 就可以刪除與代碼區(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.reibang.com/p/c59b29aaa500

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末牌芋,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子松逊,更是在濱河造成了極大的恐慌躺屁,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件经宏,死亡現(xiàn)場離奇詭異犀暑,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)烁兰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進(jìn)店門耐亏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人沪斟,你說我怎么就攤上這事广辰。” “怎么了主之?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵择吊,是天一觀的道長。 經(jīng)常有香客問我槽奕,道長几睛,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任粤攒,我火速辦了婚禮所森,結(jié)果婚禮上囱持,老公的妹妹穿的比我還像新娘。我一直安慰自己必峰,他們只是感情好洪唐,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著吼蚁,像睡著了一般。 火紅的嫁衣襯著肌膚如雪问欠。 梳的紋絲不亂的頭發(fā)上肝匆,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天,我揣著相機(jī)與錄音顺献,去河邊找鬼旗国。 笑死,一個胖子當(dāng)著我的面吹牛注整,可吹牛的內(nèi)容都是我干的能曾。 我是一名探鬼主播,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼肿轨,長吁一口氣:“原來是場噩夢啊……” “哼寿冕!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起椒袍,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤驼唱,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后驹暑,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體玫恳,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年优俘,在試婚紗的時候發(fā)現(xiàn)自己被綠了京办。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡帆焕,死狀恐怖惭婿,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情视搏,我是刑警寧澤审孽,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站浑娜,受9級特大地震影響佑力,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜筋遭,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一打颤、第九天 我趴在偏房一處隱蔽的房頂上張望暴拄。 院中可真熱鬧,春花似錦编饺、人聲如沸乖篷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽撕蔼。三九已至,卻和暖如春秽誊,著一層夾襖步出監(jiān)牢的瞬間鲸沮,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工锅论, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留讼溺,地道東北人。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓最易,卻偏偏與公主長得像怒坯,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子藻懒,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評論 2 354

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