iOS 监听系统音量按钮(持续更新)

Appdelegate.m中,添加头文件和系统监听代码

#import <AVFoundation/AVFoundation.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    //监听系统声音
    
    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];
    
    
    
    return YES;
}

在需要监听的页面中添加通知,例子:ViewController.m中

- (void)viewDidLoad {
    [super viewDidLoad];
  
    
    [[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-系统音量:%ld", volume);
    
}

运行即可。

原文地址:https://www.cnblogs.com/gaozhang12345/p/10188629.html