Larme 的答案在 iOS 7 中被弃用(volume
属性MPMusicPlayer
和iPodMusicPlayer
方法)。试试这个来获取AVAudioPlayer
当前歌曲的实例(但是,当我这样做时,出于某种奇怪的原因,它总是返回-120 dB
):
AVAudioPlayer *somePlayer = [AVAudioPlayer new];
__autoreleasing NSError* error;
somePlayer = [somePlayer initWithContentsOfURL:[[[MPMusicPlayerController systemMusicPlayer] nowPlayingItem] valueForProperty:MPMediaItemPropertyAssetURL] error:&error];
somePlayer.currentTime = [[MPMusicPlayerController systemMusicPlayer] currentPlaybackTime];
somePlayer.volume = 0;
[somePlayer play];
[somePlayer setMeteringEnabled:YES];
[somePlayer updateMeters];
NSMutableArray* amps = [NSMutableArray array];
if (error != nil) {
NSLog(@"error: %@", error.debugDescription);
}
for (int i = 0; i < somePlayer.numberOfChannels; i++) {
[amps addObject:@(([somePlayer peakPowerForChannel:i] + 160.0) / 160.0)];
NSLog(@"Amplitude: %f db for channel %i", [somePlayer averagePowerForChannel:i], i);
}
float amp = 0;
for (NSNumber *x in amps) {
amp += [x floatValue];
}
amp /= amps.count;
NSLog(@"amp: %f", amp);