【问题标题】:How to fetch songs from ipodlibrary and play using AVPlayer如何从 ipodlibrary 获取歌曲并使用 AVPlayer 播放
【发布时间】:2012-07-18 20:13:08
【问题描述】:

我想从 ipod 库中选择歌曲并使用 avplayer 播放我希望音乐在应用程序进入后台后继续播放我是 iOS 编程新手,谁能帮帮我..

谢谢

【问题讨论】:

  • 我想去夏威夷度过一个全价的带薪假期:)
  • 问得越错,得到的答案就越错
  • 我在 mpmusicplayercontroller 类上工作过……但它不支持后台播放。听说avplayer支持后台播放

标签: iphone objective-c ios xcode


【解决方案1】:

要允许用户从他们的音乐库中挑选一首(或多首歌曲),请使用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 键下的数组中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多