一:监听系统音量
1:添加 #import
2:在 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 添加
//监听系统声音
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];
3:在需要添加监听的地方监听音量
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
//系统声音改变
-(void)volumeChanged:(NSNotification *)notification
{
float volume = [[[notification userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
NSLog(@"FlyElephant-系统音量:%f", volume);
}
二:设置系统音量
#import
//初步同步系统的音量跟耳机初步音量达成一致
MPVolumeView *volumeView = [MPVolumeView new];
volumeView.showsRouteButton = NO;
volumeView.showsVolumeSlider = NO;
[self.view addSubview:volumeView];
// __weak __typeof(self)weakSelf = self;
[[volumeView subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[UISlider class]]) {
//__strong __typeof(weakSelf)strongSelf = weakSelf;
volumeViewSlider = obj;//UISlider* volumeViewSlider;
*stop = YES;
}
}];
[volumeViewSlider setValue:volumeF animated:YES];