我想从ipod Library中选择歌曲并使用avplayer播放我希望音乐能够继续播放,即使应用程序进入后台我是iOS编程新手也可以帮助我...
谢谢
要允许用户从他们的音乐库中选择一首歌曲(或多首歌曲),请使用该MPMediaPickerController
课程.
-(void) pickSong { // Create picker view MPMediaPickerController* picker = [[MPMediaPickerController alloc] init]; picker.delegate = self; // Check how to display if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) { // Show in popover [popover dismissPopoverAnimated:YES]; popover = [[UIPopoverController alloc] initWithContentViewController:picker]; [popover presentPopoverFromBarButtonItem:self.navigationItem.rightBarButtonItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; } else { // Present modally [self presentViewController:picker animated:YES completion:nil]; } }
self.navigationItem.rightBarButtonItem
如果您没有通过标题栏右侧的按钮显示,请更改.
然后你需要通过实现委托来监听结果:
用户取消选择时调用:
-(void) mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker { // Dismiss selection view [self dismissViewControllerAnimated:YES completion:nil]; [popover dismissPopoverAnimated:YES]; popover = nil; }
当用户选择某些内容时调用:
-(void) mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection { // Dismiss selection view [self dismissViewControllerAnimated:YES completion:nil]; [popover dismissPopoverAnimated:YES]; popover = nil; // Get AVAsset NSURL* assetUrl = [mediaItemCollection.representativeItem valueForProperty:MPMediaItemPropertyAssetURL]; AVURLAsset* asset = [AVURLAsset URLAssetWithURL:assetUrl options:nil]; // Create player item AVPlayerItem* playerItem = [AVPlayerItem playerItemWithAsset:asset]; // Play it AVPlayer* myPlayer = [AVPlayer playerWithPlayerItem:playerItem]; [myPlayer play]; }
你UIPopoverController* popover;
的班级.h文件需要一个.你也应该留在myPlayer
某个地方......
要允许音乐在后台继续audio
,请在UIBackgroundModes
键下的Info.plist中为数组添加一个字符串.