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

前端之家收集整理的这篇文章主要介绍了iphone – 如何从ipodlibrary获取歌曲并使用AVPlayer播放前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从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 …

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

猜你在找的Xcode相关文章