Reputation: 124
I really new to Obj-C and iOS development, i found very much useful information here, but here is a question I didn't find the answer.
I got instance of AVQueuePlayer
which plays audio stream from url.
How can I know that audio stream is loaded? For example when I press "Play" button, there is couple of seconds delay between a button press and actual start of streaming.
I looked at developer.apple.com library and didn't find any method that I can use to check status of AVQueuePlayer
. There is one in AVPLayer
, but AVPlayer
is not supporting stream over http as far as i know.
Thank you.
Upvotes: 1
Views: 2873
Reputation: 49
I am not sure what you mean by "loaded": do you mean when the item is fully loaded or when the item is ready to play?
AVQueuePlayer
supports http streams (HTTP Live and files) in the same way as AVPlayer
. You should review the AVFoundation Programming Guide, Handling Different Types of Asset.
The most common case is when an item is ready to play, so I'll answer that one. If you are working with iOS with AVQueuePlayer
< 4.3, you need to check the status of AVPlayerItem
by observing the value of the AVPlayerItem
status key:
static int LoadingItemContext = 1;
- (void)loadExampleItem
{
NSURL *remoteURL = [NSURL URLWithString:@"http://media.example.com/file.mp3"];
AVPlayerItem *item = [AVPlayerItem playerItemWithURL:remoteURL];
// insert the new item at the end
if (item) {
[self registerAVItemObserver:item];
if ([self.player canInsertItem:item afterItem:nil]) {
[self.player insertItem:item afterItem:nil];
// now observe item.status for when it is ready to play
}
}
}
- (void)registerAVItemObserver:(AVPlayerItem *)playerItem
{
[playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:(void*)&LoadingItemContext];
}
- (void)removeAVItemObserver:(AVPlayerItem *)playerItem
{
@try {
[playerItem removeObserver:self forKeyPath:@"status"];
}
@catch (...) { }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == &LoadingItemContext) {
AVPlayerItem *item = (AVPlayerItem*)object;
AVPlayerItemStatus status = item.status;
if (status == AVPlayerItemStatusReadyToPlay) {
// now you know you can set your player to play, update your UI...
} else if (status == AVPlayerItemStatusFailed) {
// handle error here, i.e., skip to next item
}
}
}
That is just a pre-4.3 example. After 4.3 you can load a remote file (or HTTP Live playlist) using the code example in AVFoundation Programming Guide, Preparing an Asset For Use, with loadValuesAsynchronouslyForKeys:completionHandler
. If you are using loadValuesAsynchronouslyForKeys
for a HTTP Live stream you should observe the @"tracks" property.
Upvotes: 1