主要涉及到Tips:
- 获取设备音量
- 静音模式失效
- 监听音量改变
- 设置设备音量
- 监听静音按钮
- 监听耳机拔插
1.获取设备音量
播放音频可以通过:
MPMusicPlayerController *iPod = [MPMusicPlayerController systemMusicPlayer];
float volumeLevel = iPod.volume;
播放视频可以通过:
float outputVolume = [[AVAudioSession sharedInstance] outputVolume];
推荐下面的方法,上面的在某些版本可能有问题,下面的方法兼容iOS6及以上。
2.静音模式失效
通过设置音频会话的category实现:
NSError *setCategoryError = nil;
BOOL success = [[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: &setCategoryError];
if (!success) { /* handle the error in setCategoryError */ }
这样App就不会随着手机静音键打开而静音,可在手机静音下播放声音😁
3.监听音量改变
监听音频改变私有通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
实现通过回调:
- (void)volumeChanged:(NSNotification *)notification
{
float volume = [[[notification userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]
floatValue];
// do something
}
4.设置设备音量
使用MPVolumeView
类,便利它的子views找到类为MPVolumeSlider
的滑竿。
MPVolumeView *volumeView = [[MPVolumeView alloc] init];
UISlider *volumeViewSlider = nil;
for (UIView *view in [volumeView subviews]){
if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
volumeViewSlider = (UISlider *)view;
break;
}
}
然后再通过设置volumeViewSlider
的value
即可。
_volumeViewSlider.value = someVolume;
5.监听静音按钮
参考Sound Switch - Sharkfood的实现。
使用很简单,判断是否为静音模式:
if ([SharkfoodMuteSwitchDetector shared].isMute) {
// do something
}
动态监听,通过block回调:
[SharkfoodMuteSwitchDetector shared].silentNotify = ^(BOOL silent){
// do something
};
6.监听耳机拔插
监听AVAudioSessionRouteChangeNotification
通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) name:AVAudioSessionRouteChangeNotification object:nil];
实现回调:
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification
{
NSDictionary *interuptionDict = notification.userInfo;
NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
switch (routeChangeReason) {
case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
// 耳机插入
break;
case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
// 耳机拔掉
break;
case AVAudioSessionRouteChangeReasonCategoryChange:
// called at start - also when other audio wants to play
NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
break;
}
}
网友评论