how to display selected songs from ipodLibrary played from avplayer in uitableview

旧城冷巷雨未停 提交于 2019-12-12 14:41:55

问题


I am playing songs by using AVPlayer. I am able to play it in background as well. There is a UIButton called showPlaylist. When I tap on it I need to display list of songs which I have selected from ipodLibrary in UITableView and I should be able to display artwork, number of mins remaining in the song and the artist's name if it is available in the song.

I have play and pause buttons: when I click the pause button, the song is paused but when I tap on the play button again, it goes to the ipodLibrary. How to resume play when I tap on the play button?

And when there are multiple songs in that UITableView, I want it to continue to the next track as soon as the first track completes. I was wondering how to do that.

-(IBAction)playButtonPressed:(UIButton *)sender {
  // Create picker view
  MPMediaPickerController* picker = [[MPMediaPickerController alloc] init];
  picker.delegate = self;
  if (userMediaItemCollection) {
    MusicTableViewController *controller = [[MusicTableViewController alloc]
     initWithNibName: @"MusicTableView" bundle: nil];
    controller.delegate = self;
    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController: controller animated: YES];
  } else {
    MPMediaPickerController *picker = [[MPMediaPickerController alloc]
      initWithMediaTypes: MPMediaTypeMusic];
    picker.delegate  = self;
    picker.allowsPickingMultipleItems = YES;
    picker.prompt = NSLocalizedString
      (@"Add songs to play", "Prompt in media item picker");
    [[UIApplication sharedApplication] setStatusBarStyle:
      UIStatusBarStyleDefault animated: YES];
    [self presentModalViewController: picker animated: YES];
  }
}

-(IBAction)pauseButtonPressed:(UIButton *)sender {
  [myPlayer pause];
}

-(void) mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker {
  [self dismissViewControllerAnimated:YES completion:nil];
}

-(void) mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:
  (MPMediaItemCollection *)mediaItemCollection {
  [self dismissViewControllerAnimated:YES completion:nil];
  NSURL* assetUrl = [mediaItemCollection.representativeItem
    valueForProperty:MPMediaItemPropertyAssetURL];
  AVURLAsset* asset = [AVURLAsset URLAssetWithURL:assetUrl options:nil];
  AVPlayerItem* playerItem = [AVPlayerItem playerItemWithAsset:asset];
  myPlayer = [AVPlayer playerWithPlayerItem:playerItem];
  [myPlayer play];
}

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  [self becomeFirstResponder];
}

- (BOOL)canBecomeFirstResponder {
  return YES;
}

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  [self resignFirstResponder];
}

-(void)remoteControlReceivedWithEvent:(UIEvent *)event {
  switch (event.subtype) {
    case UIEventSubtypeRemoteControlTogglePlayPause:
      if (myPlayer.rate == 0.0) {
        [myPlayer play];
      } else {
        [myPlayer pause];
      }
      break;
    case UIEventSubtypeRemoteControlPlay:
      [myPlayer play];
      break;
    case UIEventSubtypeRemoteControlPause:
      [myPlayer pause];
      break;
    default:
      break;
  }
}

回答1:


I would look into Apple's sample code "Add Music" which clearly demonstrated how to do everything you've described.

This sample application runs you through the ins and outs of populating a UITableView with the contents of a mutable copy of selected songs from the iPod library saved into a MPMediaItemCollection. It also shows how using MPMediaItems and MPMediaItemCollections you can display track specific attributes as the cells title label, etc.

  1. For populating the table view, you could set it up something like this:

    MPMediaItem *mediaItem = (MPMediaItem *)[collectionMutableCopy objectAtIndex:row];

    MPMediaItemArtwork *artwork = [mediaItem valueForProperty:MPMediaItemPropertyArtwork];

    if (mediaItem) {
        cell.textLabel.text = [mediaItem valueForProperty:MPMediaItemPropertyTitle];
        cell.detailTextLabel.text = [mediaItem valueForProperty:MPMediaItemPropertyArtist];
        if (artwork != nil) {
            cell.imageView.image = [artwork imageWithSize:CGSizeMake (40, 40)];
        }else{
            cell.imageView.image = [UIImage imageNamed:@"no_artwork.png"];
        }
    }
    
  2. Rename the button linked to the play button as "Select Music" and make a new button called "Play" with its action set to:

    - (IBAction)playMusic { [myPlayer play]; }

EDIT: Creating array from contents of MPMediaItemCollection:

NSMutableArray *collectionMutableCopy = [[NSMutableArray alloc] initWithArray:myMediaItemCollection.items];

EDIT 2: Uncomment the following lines in the project:

In - (void) registerForMediaPlayerNotifications

/*
 // This sample doesn't use libray change notifications; this code is here to show how
 //     it's done if you need it.
 [[NSNotificationCenter defaultCenter] removeObserver: self
 name: MPMediaLibraryDidChangeNotification
 object: musicPlayer];

 [[MPMediaLibrary defaultMediaLibrary] endGeneratingLibraryChangeNotifications];

 */

In - (void)dealloc

/*
 // This sample doesn't use libray change notifications; this code is here to show how
 //     it's done if you need it.
 [notificationCenter addObserver: self
 selector: @selector (handle_iPodLibraryChanged:)
 name: MPMediaLibraryDidChangeNotification
 object: musicPlayer];

 [[MPMediaLibrary defaultMediaLibrary] beginGeneratingLibraryChangeNotifications];
 */

Replace this line:

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];

With this

 [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];

 UInt32 doSetProperty = 0;
 AudioSessionSetProperty (
 kAudioSessionProperty_OverrideCategoryMixWithOthers,
 sizeof (doSetProperty),
 &doSetProperty
 );

Then add the following to your projects info.plist file




回答2:


Your problem is that your play button is doing something other than just telling the music player to play. You need one that just calls [myPlayer play]; Do all your setup somewhere other than the play button.

It's not really good coding practice to have your play button also pick songs (it's better to keep to the idea of one button -> one function). So have a button that does what's in your play button right now and then have your play button just call [myPlayer play]

As for your other question, you should look at this: Play multiple audio files using AVAudioPlayer

Just so you know, you're not really supposed to ask multiple questions in the same post. It makes it harder to give a concise, useful answer and can make the site harder to find things on.

I'm not sure if you're asking how to display song information, but I guess it's in your title. For this one, iPhone sdk - accessing current song information through an app.



来源:https://stackoverflow.com/questions/11564879/how-to-display-selected-songs-from-ipodlibrary-played-from-avplayer-in-uitablevi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!