appdelegate中加入如下代碼:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//監(jiān)聽系統(tǒng)音量變化
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryAmbient error:nil];
[session setActive:YES error:nil];
NSError *error;
[[AVAudioSession sharedInstance] setActive:YES error:&error];
//iOS9以上加上這句
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
然后在需要的頁面加入監(jiān)聽:
//監(jiān)聽系統(tǒng)音量
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChangeNotification:)name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
回調:
//系統(tǒng)音量回調
- (void)volumeChangeNotification:(NSNotification *)noti {
float volume = [[[noti userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
NSLog(@"系統(tǒng)音量:%f", volume);
}