iOS 監聽App音量的變化
方法1:
在applicationDidFinishLaunching函數裡添加
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(volumeChanged:)
name:@"AVSystemController_SystemVolumeDidChangeNotification"
object:nil];
- (void)volumeChanged:(NSNotification *)notification
{
float volume =
[[[notification userInfo]
objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]
floatValue];
DDLogVerbose(@"current volume = %f", volume);
}
弊端:當app進入後天后,依然會監聽到volume的變化
2. 對 AudioSession 添加volume變化的 listener, 可以放在startAudioSession函數裡
//add a listener for Outputvolume
AudioSessionAddPropertyListener(kAudioSessionProperty_CurrentHardwareOutputVolume ,
volumeListenerCallback,
self
);
void volumeListenerCallback (
void *inClientData,
AudioSessionPropertyID inID,
UInt32 inDataSize,
const void *inData
){
const float *volumePointer = inData;
float volume = *volumePointer;
NSLog(@"volumeListenerCallback %f", volume);
}
3. 擷取當前的volume
float volume = 0.0;
UInt32 dataSize = sizeof(float);
OSStatus status = AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareOutputVolume,
&dataSize,
&volume);