Reputation: 17424
I use AVPlayer for streaming mp3 file from the internet and it works really slow. Using profiler I found out, that it downloads entire file at first, and then starts playing. Is there any workaround for this?
Right now, I'm using this code
if let player = player {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
let item = AVPlayerItem(url: url)
player.replaceCurrentItem(with: item)
} else {
player = AVPlayer(url: url)
}
player?.play()
Things I've tried:
All the time the result is downloading a whole audio file and only then start of playing.
Please note, the issue is - player starts to play ONLY after the whole file was downloaded, while I want it to stream mp3.
Upvotes: 4
Views: 4475
Reputation: 1120
To play immediately you can try to set
player.automaticallyWaitsToMinimizeStalling = false
Upvotes: 7
Reputation: 1966
You can add an observer to when the AVPlayer gets empty buffer:
[[self.tracksPlayer currentItem] addObserver:self
forKeyPath:@"playbackBufferEmpty"
options:NSKeyValueObservingOptionNew
context:nil];
And an observer so you can know when the AVPlayer buffered enough to keep up:
[[self.tracksPlayer currentItem] addObserver:self
forKeyPath:@"playbackLikelyToKeepUp"
options:NSKeyValueObservingOptionNew
context:nil];
Then just check for that in your KVO callback:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (object == [self.tracksPlayer currentItem] &&
[keyPath isEqualToString:@"playbackBufferEmpty"]) {
if ([self.tracksPlayer currentItem].playbackBufferEmpty) {
NSLog(@"Buffer Empty");
}
} else if (object == [self.tracksPlayer currentItem] &&
[keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
if ([self.tracksPlayer currentItem].playbackLikelyToKeepUp) {
NSLog(@"LikelyToKeepUp");
}
}
}
Upvotes: 1