当前位置:  开发笔记 > IOS > 正文

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

如何解决《如何从ipodlibrary获取歌曲并使用AVPlayer播放》经验,为你挑选了1个好方法。

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

谢谢



1> jjv360..:

要允许用户从他们的音乐库中选择一首歌曲(或多首歌曲),请使用该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某个地方......

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

推荐阅读
和谐啄木鸟
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有