音樂(lè)播放器

  • 1.搭建音樂(lè)播放器的界面
    • 對(duì)于這個(gè)音樂(lè)播放器我只實(shí)現(xiàn)了播放 暫停 下一曲 上一曲 停止 音量加減 和從歌曲列表中選歌并播放的功能 更多功能 歡迎大家參考我的代碼 進(jìn)行修改,代碼中有些不妥地方,還望各位大神指出。
  • 整體界面搭建出來(lái) 是這個(gè)樣子:


  • 這個(gè)是播放列表的樣子 我把它做成半透明的樣式;


  • 在搭建界面的時(shí)候 我們可以使用XIB來(lái)畫(huà) 這樣可以節(jié)約很多開(kāi)發(fā)的時(shí)間 這個(gè)例子中 大多界面的地方我還是使用的純代碼實(shí)現(xiàn) 因?yàn)榧兇a編寫(xiě)雖然有點(diǎn)耽誤時(shí)間 但是將來(lái)進(jìn)行版本控制的時(shí)候 非常方便.在使用XIB的時(shí)候 要注意的問(wèn)題:
    • 當(dāng)你畫(huà)了一個(gè)控件 點(diǎn)擊右上角的輔助編輯器 你可以使用按住Ctrl 加鼠標(biāo)左鍵 拖到你的編輯器 然后為你的控件取名字. 當(dāng)你想刪除的時(shí)候 一定要點(diǎn)擊storyBord 在你要?jiǎng)h除的空間的上面 右鍵 然后點(diǎn)擊叉叉 就可以刪除與代碼區(qū)的綁定 。如果要再次綁定只需要再次Ctrl加鼠標(biāo)左鍵 拖過(guò)來(lái).
      代碼區(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:@"月半小夜曲",@"后會(huì)無(wú)期",@"靜靜看著你",@"李白",@"喜歡你",@"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:@"后會(huì)無(wú)期" ofType:@"mp3"];
      NSURL *fileUrl = [NSURL fileURLWithPath:filename];
      //先拿到文件 才能拿到數(shù)據(jù) 才能刷新
      [self updateUI:fileUrl];
      MyPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
      //設(shè)置支持后臺(tái)播放后臺(tái)播放
      //獲得當(dāng)前音頻會(huì)話(huà)對(duì)象的單例
      AVAudioSession audioSession = [AVAudioSession sharedInstance];
      [audioSession setActive:YES error:nil];
      [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
      //打開(kāi)項(xiàng)目 capabilities---> background modes--- > 打開(kāi)audio and airplay 設(shè)置支持后臺(tái)播放
      //打開(kāi)項(xiàng)目 capabilities---> background modes---> 打開(kāi)remote notifications 設(shè)置支持耳機(jī)
      [[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
      //聲道
      // player.pan = -1;
      //音樂(lè)大小 0~1 最大值可以修改 是一種軟修改
      //MyPlayer.volume = 1;
      //文件播放速率 用于快進(jìn) 快退
      //player.enableRate = YES;
      //player.rate = 4;
      //跳過(guò)20s再播放
      //MyPlayer.currentTime = 270;
      MyPlayer.delegate = self;
      //文件緩存
      //[MyPlayer prepareToPlay];
      //播放音樂(lè)
      // [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 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:@"月半小夜曲",@"后會(huì)無(wú)期",@"靜靜看著你",@"李白",@"喜歡你",@"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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容