2012-07-18 86 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

相關問題