2012-07-18 108 views
4

我想从ipod Library中选择歌曲并使用avplayer播放我希望音乐可以在应用程序转到背景后继续播放我是iOS编程新手,任何人都可以帮助我出..如何从ipodlibrary获取歌曲并使用AVPlayer播放

感谢

+4

而且我想要一个花费全月的长假到夏威夷:) – 2012-07-18 11:26:56

+0

问题的责难者被问到了 - 溃败者的回答得到了 – 2012-07-18 11:34:23

+0

我曾经在mpmusicplayercontroller类上工作过......但它不支持后台播放。我听说avplayer支持后台播放 – coded 2012-07-18 13:03:23

回答

7

要允许用户从他们的音乐库中选择一首歌曲(或歌曲),使用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;在你的cla ss .h文件。您还应该在某处保留myPlayer ...

要允许音乐在后台继续播放,请在UIBackgroundModes下的Info.plist中将数字字符串添加到audio

+0

感谢它像一个魅力工作 – coded 2012-07-19 15:52:29

相关问题