我想从iPod图书馆中选择歌曲并使用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;
。同时,您应该在某处保留myPlayer
...UIBackgroundModes
键下的数组中添加一个audio
字符串。