如何从iPod库中获取歌曲并使用AVPlayer播放

4
我想从iPod图书馆中选择歌曲并使用AVPlayer播放,我希望音乐在应用程序进入后台后仍然继续播放。由于我是iOS编程的新手,有人能帮我吗?
谢谢!

4
我希望你能给我一个全程免费的为期一个月的夏威夷假期 :) - Aleks G
问题提得越错,得到的答案就越错。 - John Smith
我曾经使用过MPMusicPlayerController类……但它不支持后台播放。我听说AVPlayer支持后台播放。 - coded
1个回答

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...
为了允许音乐在后台继续播放,请在您的Info.plist中的UIBackgroundModes键下的数组中添加一个audio字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接