iOS监听音量调节事件

2021-11-08  本文已影响0人  东方诗空

方法一:

添加AudioToolbox.framework
Appdelegate.m中,添加头文件 #includ

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions

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);
 
}

方法二:

添加通知:

[[AVAudioSession sharedInstance] addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:(void *)[AVAudioSession sharedInstance]];
 
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if(context == (__bridge void *)[AVAudioSession sharedInstance]){
        float newValue = [[change objectForKey:@"new"] floatValue];
        float oldValue = [[change objectForKey:@"old"] floatValue];
        // TODO: 这里实现你的逻辑代码
    }
}


方法三:
这中方法较为简单实用

添加MediaPlayer.framework (可以让调节音量的view 不显示在界面 如果没有这需求可以不添加)

AVFoundation.framework

在Appdelegate.m中

导入#import <AVFoundation/AVFoundation.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 


添加

AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSError *error;
    [[AVAudioSession sharedInstance] setActive:YES error:&error];
    //注,ios9上不加这一句会无效
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

在使用的ViewController的- (void)viewDidLoad方法中添加通知

//监听音量调节
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];

-(void)volumeChanged:(NSNotification *)noti
 
{                                   
 
    float volume =
 
    [[[noti userInfo]
 
      objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]
 
     floatValue];
 
    NSLog(@"volumn is %f", volume);
    //这里做你想要的进行的操作
 }

注意事项 1 : 此方法使用时候测试到 长按home键调出Siri后也会调用这个调用这个通知方法 以及再点击home键退出Siri时候还会调一次这个方法

-(void)volumeChanged:(NSNotification *)noti
 
{                                   
 
    float volume =
 
    [[[noti userInfo]
 
      objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]
 
     floatValue];
 
    NSLog(@"volumn is %f", volume);
    NSString *str1 = [[noti userInfo]objectForKey:@"AVSystemController_AudioCategoryNotificationParameter"];
    NSString *str2 = [[noti userInfo]objectForKey:@"AVSystemController_AudioVolumeChangeReasonNotificationParameter"];
    if (([str1 isEqualToString:@"Audio/Video"] || [str1 isEqualToString:@"Ringtone"]) && ([str2 isEqualToString:@"ExplicitVolumeChange"]))
    {
<pre name="code" class="objc">      //这里做你想要的进行的操作


注意事项 2 : 应用进入后台运行时不让响应音量调节事件

解决方案: 添加一个BOOL变量isIntoBg 在- (void)viewDidLoad方法中添加通知

//进入后台
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(intoBackg) name:UIApplicationDidBecomeActiveNotification object:nil];
    //进入前台
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(returnBackg) name:UIApplicationWillResignActiveNotification object:nil];

- (void)intoBackg
{
    NSLog(@"***************后台出来*****************");
    isIntoBg = NO;
}
 
- (void)returnBackg
{
    NSLog(@"***************进入后台*****************");
    isIntoBg = YES;
}



当然通知方法中也要进行判断一下


-(void)volumeChanged:(NSNotification *)noti
 
{                                   
 
    float volume =
 
    [[[noti userInfo]
 
      objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]
 
     floatValue];
 
    NSLog(@"volumn is %f", volume);
    NSString *str1 = [[noti userInfo]objectForKey:@"AVSystemController_AudioCategoryNotificationParameter"];
    NSString *str2 = [[noti userInfo]objectForKey:@"AVSystemController_AudioVolumeChangeReasonNotificationParameter"];
    //此处判断将音量调节和铃声调节都包括进来进行响应
    if (([str1 isEqualToString:@"Audio/Video"] || [str1 isEqualToString:@"Ringtone"]) && ([str2 isEqualToString:@"ExplicitVolumeChange"]))
    {
       if(isIntoBg == NO){           
      //这里做你想要的进行的操作
       }
    }
 
 }


注意事项 3: 只在这个界面响应监听音量调节的事件

解决方案:

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    isIntoBg = NO;
}
 
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    isIntoBg = YES;
}



注意事项 4: 不显示系统的音量视图

解决方案:

添加MediaPlayer.framework

导入#import <MediaPlayer/MediaPlayer.h>

在viewdidload中新增一个音量视图替换掉系统的音量视图

MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
    
    volumeView.center = CGPointMake(-550,370);//设置中心点,让音量视图不显示在屏幕中
    
    [volumeView sizeToFit];
    
    [self.view addSubview:volumeView];


上一篇下一篇

猜你喜欢

热点阅读