[绍棠] 播放器检测系统音量键调节音量的变化并自定义音量界面

来源:互联网 发布:房产端口是什么意思 编辑:程序博客网 时间:2024/04/30 22:59

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

    MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];

    volumeView.center = CGPointMake(-550,370);//设置中心点,让音量视图不显示在屏幕中

    [volumeView sizeToFit];

    [self.view addSubview:volumeView];

 

 到此监听音量调节事件就搞定了


添加监听

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(volumeChanged:)name:@"AVSystemController_SystemVolumeDidChangeNotification"object:nil];


方法处理

- (void)volumeChanged:(NSNotification *)notification {

    float volume = [[[notificationuserInfo]objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]

     floatValue];

}


/// 注意, 该消息除了监听音量键之外,应用从后台切换到前台也会发送该消息,所以,还需要判断消息的userInfo的字段AVSystemController_AudioVolumeChangeReasonNotificationParameter,确定发送消息的理由,value值为ExplicitVolumeChange就是我们所需要的。

- (void)volumeChanged:(NSNotification *)notification {

    if ([notification.nameisEqualToString:@"AVSystemController_SystemVolumeDidChangeNotification"]) {

        NSDictionary *userInfo = notification.userInfo;

        NSString *reasonStr = userInfo[@"AVSystemController_AudioVolumeChangeReasonNotificationParameter"];

        if ([reasonStrisEqualToString:@"ExplicitVolumeChange"]) {

            float volume = [[[notificationuserInfo]objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]floatValue];

        }

    }

}




销毁

- (void)dealloc{

    DDLogInfo(@"%@ is dealloc",self);

    [NSObjectcancelPreviousPerformRequestsWithTarget:self];

   [[NSNotificationCenterdefaultCenter]removeObserver:selfname:@"AVSystemController_SystemVolumeDidChangeNotification"object:nil];

    [[NSNotificationCenterdefaultCenter]removeObserver:self];

}


0 0