如何从ipodlibrary获取歌曲并使用AVPlayer播放

时间:2012-07-18 11:24:48

标签: iphone objective-c ios xcode

我想从ipod Library中选择歌曲并使用avplayer播放我希望音乐能够在应用程序进入后台后继续播放我是iOS编程新手,任何人都可以帮助我...

谢谢

1 个答案:

答案 0 :(得分: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]; 

}

您的班级.h文件中需要UIPopoverController* popover;。你还应该保留myPlayer某个地方......

要允许音乐在后台继续,请在audio键下的Info.plist中的数组中添加UIBackgroundModes字符串。