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];
到此監聽音量調節事件就搞定了