转载自: https://www.cnblogs.com/demodashi/p/8509609.html
四、距离传感器
①概述
距离传感器: 感应是否有其他物体靠近屏幕,iPhone手机中内置了距离传感器,位置在手机的听筒附近,当我们在打电话或听微信语音的时候靠近听筒,手机的屏幕会自动熄灭,这就靠距离传感器来控制
- 首先打开距离传感器,然后添加通知UIDeviceProximityStateDidChangeNotification监听有物品靠近还是离开,从而做出操作,记得最后要关闭距离传感器,有始有终哦。
②实现
- 示例中是默认用扬声器播放音乐,当有物体(比如耳朵)靠近听筒附近时就切换听筒播放音乐,物体离开后就继续用扬声器播放音乐。
- (void)distanceSensor{
// 打开距离传感器
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
// 通过通知监听有物品靠近还是离开
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateDidChange:) name:UIDeviceProximityStateDidChangeNotification object:nil];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//默认情况下扬声器播放
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive:YES error:nil];
NSString * path = [[NSBundle mainBundle] pathForResource:@"SeeYouAgain" ofType:@"mp3"];
if(path == nil){
return;
}
_play = [[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:path]];
[_play play];
}
- (void)proximityStateDidChange:(NSNotification *)note
{
if ([UIDevice currentDevice].proximityState) {
NSLog(@"有东西靠近");
//听筒播放
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
} else {
NSLog(@"有物体离开");
//扬声器播放
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
}
}
- (void)dealloc{
[_play pause];
_play = nil;
//关闭距离传感器
[UIDevice currentDevice].proximityMonitoringEnabled = NO;
[self removeObserver];
}
本文介绍如何使用iPhone内置的距离传感器控制音频播放方式。当物体靠近听筒时,音乐从扬声器切换到听筒播放;物体远离时,再切换回扬声器播放。涉及UIDeviceProximityStateDidChangeNotification通知及AVAudioSession类别。
271

被折叠的 条评论
为什么被折叠?



