iOS播放器常用功能
强制横屏
在播放器中常见强制横屏,例如,如下这种:
OC实现代码如下:
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {SEL selector = NSSelectorFromString(@"setOrientation:");NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];[invocation setSelector:selector];[invocation setTarget:[UIDevice currentDevice]];int val = orientation;// 从2开始是因为0 1 两个参数已经被selector和target占用[invocation setArgument:&val atIndex:2];[invocation invoke];}
拖动调节音量
在播放器器中,通常是拖动来调节音量。需要使用到MPVolumeView
MPVolumeView
是Media Player Framework中的一个UI组件,直接包含了对系统音量和Airplay设备的音频镜像路由的控制功能。其中包含一个MPVolumeSlider
的subview
用来控制音量。这个MPVolumeSlider
是一个私有类,我们无法手动创建此类,但这个类是UISlider的子类。
遍历MPVolumeSlider
的subview
获取到这个slider
MPVolumeView *volumeView = [[MPVolumeView alloc] init];
for (UIView *view in [volumeView subviews]){if ([view.class.description isEqualToString:@"MPVolumeSlider"]){_volumeSlider = (UISlider*)view;break;}
}
添加对应的拖动手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panDirection:)];
pan.delegate = self;
[self.view addGestureRecognizer:pan];
对应的拖动事件为,这里仅仅是一个简单的例子,上下拖动时改变slider的value
:
/*** pan手势事件** @param pan 拖动手势*/- (void)panDirection:(UIPanGestureRecognizer *)pan{CGPoint veloctyPoint = [pan velocityInView:self.view];switch (pan.state) {case UIGestureRecognizerStateBegan:{ // 开始移动// 使用绝对值来判断移动的方向CGFloat x = fabs(veloctyPoint.x);CGFloat y = fabs(veloctyPoint.y);if (x > y) {// 水平移动_verticalPan = NO;}else if (x < y){// 垂直移动_verticalPan = YES;}break;}case UIGestureRecognizerStateChanged:{ // 正在移动if (_verticalPan) {self.volumeSlider.value -= veloctyPoint.y / 10000;}}case UIGestureRecognizerStateEnded:{ // 移动停止}default:break;}}
结果要在真机上测试才行,结果如下:
调节亮度
通洞调节亮度跟上面差不多,如下:
[UIScreen mainScreen].brightness -= veloctyPoint.x / 10000;
只是没有提示,所以自己要自定义一个提示框BrightnessView。在中BrightnessView使用KVO观察[UIScreen mainScreen]
的brightness的变化
[[UIScreen mainScreen] addObserver:selfforKeyPath:@"brightness"options:NSKeyValueObservingOptionNew context:NULL];
在亮度变化后作出相应的调整:
- (void)observeValueForKeyPath:(NSString *)keyPathofObject:(id)objectchange:(NSDictionary *)changecontext:(void *)context {CGFloat sound = [change[@"new"] floatValue];//处理对应的逻辑}