I know it is possible to play iPod Songs using AVPlayer, but I cannot figure out how to initialize the AVAudioPlayer
with an iPod song URL using initWithContentsOfURL
. When I try, the AVAudioPlayer
returns NULL upon initialization.
I need to use AVAudioPlayer
because I need to use its delegate method audioPlayerDidFinishPlaying
for further processing when my app runs in the background (i.e. the AVAudioPlayer
delegate method audioPlayerDidFinishPlaying
gets called if the app is running in the background. But the AVPlayer
does not provide delegate methods, so you can only use notifications which don't run in the background).
The following code is for playing an iPod song with the AVPlayer.
- (void)viewDidLoad {
[super viewDidLoad];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSError *error = nil;
[session setActive:YES error:&error];
MPMediaQuery *query = [MPMediaQuery songsQuery];
NSArray *collection = [query items];
MPMediaItem *item = [collection objectAtIndex:0];
NSLog(@"%@",[item valueForProperty:MPMediaItemPropertyTitle]);
NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
AVPlayer *player = [[AVPlayer alloc]initWithURL:url]; // <-- Line to Replace
[player play];
}
This works great. But if I replace the second to last line with the following:
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
the call to initWithContentsOfURL
returns NULL.
Any thoughts about why this returns NULL when I use AVAudioPlayer
, but returns an initialized player when I use AVPlayer
?
According the the Technical Q&A http://developer.apple.com/library/ios/#qa/qa1634/_index.html, "the URL used with initWithContentsOfURL: must be a File URL (file://). That is, a local path."
When I obtain the url for the song in my iPod Library, the path is:
ipod-library://item/item.mp3?id=-4017276016911605928
Would you say that this path to my iPod library is not considered a "local path" or would you consider it a bug that initWithContentsOfURL
is returning NULL?
Thoughts anyone?
You have sort of answered your own question because from what I can gather it is the url path that is important for AVAudioPlayer
, and it has to be local to the bundle. There is an example of using AVPlayer
with notifications, search AVPlayerDemo
for playerItemDidReachEnd
but I cannot tell you whether it runs in background or foreground.