AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionSetActive(true);
AudioSessionAddPropertyListener(kAudioSessionProperty_CurrentHardwareOutputVolume ,
volumeListenerCallback,
(__bridge void *)(self)
);
外加回调函数
void volumeListenerCallback (
void *inClientData,
AudioSessionPropertyID inID,
UInt32 inDataSize,
const void *inData
){
const float *volumePointer = inData;
float volume = *volumePointer;
NSLog(@"volumeListenerCallback %f", volume);
}
搞定。
方法二:较为简单实用
添加MediaPlayer.framework
AVFoundation.framework
在Appdelegate.m中
在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions方法中添加
NSError *error;
[[AVAudioSession sharedInstance] setActive:YES error:&error];//加上这句可以在按音量键的时候不显示音量提示视图
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(volumeChanged:)
name:@"AVSystemController_SystemVolumeDidChangeNotification"
object:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];//注,ios9上不加这一句会无效,加了这一句后,
//在移除通知时候加上这句[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
然后添加方法
-(void)volumeChanged:(NSNotification *)noti
{
float volume =
[[[noti userInfo]
objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]
floatValue];
NSLog(@"volumn is %f", volume);
}
在viewdidload中新增一个音量视图替换掉系统的音量视图
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
volumeView.center = CGPointMake(-550,370);//设置中心点,让音量视图不显示在屏幕中
[volumeView sizeToFit];
[self.view addSubview:volumeView];
到此监听音量调节事件就搞定了