I am trying to show a meter graph in my app which uses AVPlayer to stream live audio streams.
I know for AVAudioPlayer there is a way as per: Trying to understand AVAudioPlayer and audio level metering
which uses peakPowerForChannel
But AVAudioPlayer doesn't work for audio streams.
Is there something similar for AVPlayer? Or is there any other way I can get the power values from the AVPlayer?
Code:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
if (self.avplayer) {
[self.avplayer replaceCurrentItemWithPlayerItem:nil];
}
AVURLAsset *avAsset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:@"http://broadcast.infomaniak.net/radionova-high.mp3"] options:nil];
NSArray *keys = @[@"playable"];
[avAsset loadValuesAsynchronouslyForKeys:keys completionHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
AVPlayerItem *newItem = [[AVPlayerItem alloc] initWithAsset:avAsset];
if (!self.avplayer) {
self.avplayer = [[AVPlayer alloc] initWithPlayerItem:newItem];
} else {
[self.avplayer replaceCurrentItemWithPlayerItem:newItem];
}
[self.avplayer addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial) context:nil];
[self.avplayer addObserver:self forKeyPath:@"rate" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial) context:nil];
});
}];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
NSLog(@"%@ called",keyPath);
if ( [keyPath isEqualToString:@"status"]) {
[self.avplayer play];
} else if ( [keyPath isEqualToString:@"rate"]) {
if (self.avplayer.rate) {
NSLog(@"Playing...");
[[NSNotificationCenter defaultCenter] postNotificationName:@"currentPlayingChangedToPlay" object:nil];
} else {
NSLog(@"Not playing...");
[[NSNotificationCenter defaultCenter] postNotificationName:@"currentPlayingChangedToPause" object:nil];
}
}
}