Ios – AVAUdioPlayer – changing current URL

avaudioplayerios

In my audio player app, if I hit the fast forward button – the player must find the next song in the playlist and play it. What I do is I get the URL from the next song, and try to put it in the background (background is an instance of AVAudioPlayer*) url field, but that property is read only. So what I'm actually doing – I'm calling the initWithContentsOfURL method (again) to set the URL like this :

[self.background initWithContentsOfURL:
[[_playlist.collection objectAtIndex:currentIndex] songURL] error:nil];

Is this legit? I mean, the compiler tells me that the expression result is unused, but it actually works.
Is there another way of doing it? Thanks 😉

Best Answer

For playing more than one URL, or effectively changing the URL, use the subclass AVQueuePlayer.

AVQueuePlayer is a subclass of AVPlayer you use to play a number of items in sequence.

Example:

NSString *fooVideoPath = [[NSBundle mainBundle] pathForResource:@"tommy" ofType:@"mov"];
NSString *barVideoPath = [[NSBundle mainBundle] pathForResource:@"pamela" ofType:@"mp4"];

AVPlayerItem *fooVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:fooVideoPath]];
AVPlayerItem *barVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:barVideoPath]];

self.queuePlayer = [AVQueuePlayer queuePlayerWithItems:[NSArray arrayWithObjects:fooVideoItem, barVideoItem,nil]];
[self.queuePlayer play];

// things happening...

[self.queuePlayer advanceToNextItem];
Related Topic