- 1.搭建音乐播放器的界面
- 对于这个音乐播放器我只实现了播放 暂停 下一曲 上一曲 停止 音量加减 和从歌曲列表中选歌并播放的功能 更多功能 欢迎大家参考我的代码 进行修改,代码中有些不妥地方,还望各位大神指出。
-
整体界面搭建出来 是这个样子:
-
这个是播放列表的样子 我把它做成半透明的样式;
- 在搭建界面的时候 我们可以使用XIB来画 这样可以节约很多开发的时间 这个例子中 大多界面的地方我还是使用的纯代码实现 因为纯代码编写虽然有点耽误时间 但是将来进行版本控制的时候 非常方便.在使用XIB的时候 要注意的问题:
- 当你画了一个控件 点击右上角的辅助编辑器 你可以使用按住Ctrl 加鼠标左键 拖到你的编辑器 然后为你的控件取名字. 当你想删除的时候 一定要点击storyBord 在你要删除的空间的上面 右键 然后点击叉叉 就可以删除与代码区的绑定 。如果要再次绑定只需要再次Ctrl加鼠标左键 拖过来.
代码区:
#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];
//先拿到文件 才能拿到数据 才能刷新
[self updateUI:fileUrl];
MyPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
//设置支持后台播放后台播放
//获得当前音频会话对象的单例
AVAudioSession audioSession = [AVAudioSession sharedInstance];
[audioSession setActive:YES error:nil];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
//打开项目 capabilities---> background modes--- > 打开audio and airplay 设置支持后台播放
//打开项目 capabilities---> background modes---> 打开remote notifications 设置支持耳机
[[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
//声道
// player.pan = -1;
//音乐大小 0~1 最大值可以修改 是一种软修改
//MyPlayer.volume = 1;
//文件播放速率 用于快进 快退
//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, 4HEIGHT/7, 30, 20)];
[volumeStepper addTarget:self action:@selector(volumeChange:) forControlEvents:UIControlEventValueChanged];
volumeStepper.minimumValue = 0;
volumeStepper.maximumValue = 3;
volumeStepper.stepValue = 1;
//设置控制器背景图片
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 didSele ctRowAtIndexPath:(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;
}
//进度条改变的回调方法
-(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;
}
//播放结束
-(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{
//代表和文件相关的数据
AVURLAsset *assset = [[AVURLAsset alloc]initWithURL:fileUrl options:nil];
//[assset availableMetadataFormats];//元数据的格式
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
- 当你画了一个控件 点击右上角的辅助编辑器 你可以使用按住Ctrl 加鼠标左键 拖到你的编辑器 然后为你的控件取名字. 当你想删除的时候 一定要点击storyBord 在你要删除的空间的上面 右键 然后点击叉叉 就可以删除与代码区的绑定 。如果要再次绑定只需要再次Ctrl加鼠标左键 拖过来.
网友评论