一:
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFAudio.h>
@property(nonatomic,strong)UISlider *sliderView;
@property(nonatomic,assign)NSIntegercurrentTime;
二.隐藏系统音量提示框
- (void)viewDidLoad {
[superviewDidLoad];
self.view.backgroundColor = [UIColorredColor];
MPVolumeView *volumeView = [[MPVolumeViewalloc] initWithFrame: CGRectZero];
volumeView.clipsToBounds = YES;
[self.viewaddSubview: volumeView];
self.sliderView = [[UISlideralloc]init];
self.sliderView.frame = CGRectMake(100, 100, 200, 10);
self.sliderView.maximumValue = 1;
self.sliderView.minimumValue = 0;
// self.sliderView.backgroundColor = [UIColor blueColor];
self.sliderView.tintColor = [UIColoryellowColor];
self.sliderView.thumbTintColor = [UIColorclearColor];//隐藏滑块
[self.viewaddSubview:self.sliderView];
[selfsettingVolume];
}
三.
// 设置音量相关
- (void)settingVolume {
//监听系统音量变化
AVAudioSession *session = [AVAudioSessionsharedInstance];
[session setCategory:AVAudioSessionCategoryAmbienterror:nil];
[session setActive:YESerror:nil];
NSError *error;
[[AVAudioSessionsharedInstance] setActive:YESerror:&error];
[[UIApplicationsharedApplication] beginReceivingRemoteControlEvents];
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(volumeChangeNotification:)name:@"AVSystemController_SystemVolumeDidChangeNotification"object:nil];
}
// 音量改变
- (void)volumeChangeNotification:(NSNotification *)noti {
if (self.sliderView.alpha == 0.0) {
[UIViewanimateWithDuration:0.25animations:^{
self.sliderView.alpha = 1.0;
}];
}
float volume = [[[noti userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
self.sliderView.value = volume;
self.currentTime = [NSDatedate].timeIntervalSince1970;
// 两秒后消失
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSTimeInterval nowTime = [NSDatedate].timeIntervalSince1970;
// 容错处理,处理用户连续按音量加减时的情况
if ((nowTime - self.currentTime) >= 2.0) {
[UIViewanimateWithDuration:0.25animations:^{
self.sliderView.alpha = 0.0;
} ];
}
});
}