我想从 ipod 库中选择歌曲并使用 avplayer 播放我希望即使在应用程序进入后台后音乐也能继续播放我是 iOS 编程新手,谁能帮帮我..
谢谢
我想从 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;
在你的类 .h 文件中。你也应该保留在myPlayer
某个地方......
要让音乐在后台继续播放,请将audio
字符串添加到 Info.plist 中UIBackgroundModes
键下的数组中。