主要涉及到Tips:

  • 获取设备音量
  • 静音模式失效
  • 监听音量改变
  • 设置设备音量
  • 监听静音按钮
  • 监听耳机拔插

1.获取设备音量

播放音频可以通过:

1
2
MPMusicPlayerController *iPod = [MPMusicPlayerController systemMusicPlayer];
float volumeLevel = iPod.volume;

播放视频可以通过:

1
float outputVolume = [[AVAudioSession sharedInstance] outputVolume];

推荐下面的方法,上面的在某些版本可能有问题,下面的方法兼容iOS6及以上

2.静音模式失效

通过设置音频会话的category实现:

1
2
3
4
5
NSError *setCategoryError = nil;
BOOL success = [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback
                                                    error: &setCategoryError];

if (!success) { /* handle the error in setCategoryError */ }

这样App就不会随着手机静音键打开而静音,可在手机静音下播放声音😁

3.监听音量改变

监听音频改变私有通知:

1
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];

实现通过回调:

1
2
3
4
5
6
7
- (void)volumeChanged:(NSNotification *)notification
{
    float volume = [[[notification userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]
     floatValue];

     // do something
}

4.设置设备音量

使用MPVolumeView类,便利它的子views找到类为MPVolumeSlider的滑竿。

1
2
3
4
5
6
7
8
MPVolumeView *volumeView = [[MPVolumeView alloc] init];
UISlider *volumeViewSlider = nil;
  for (UIView *view in [volumeView subviews]){
      if ([view.class.description isEqualToString:@"MPVolumeSlider"]) {
          volumeViewSlider = (UISlider *)view;
          break;
      }
  }

然后再通过设置volumeViewSlidervalue即可。

1
_volumeViewSlider.value = someVolume;

5.监听静音按钮

参考Sound Switch - Sharkfood的实现。

使用很简单,判断是否为静音模式:

1
2
3
if ([SharkfoodMuteSwitchDetector shared].isMute) {
    // do something
}

动态监听,通过block回调:

1
2
3
[SharkfoodMuteSwitchDetector shared].silentNotify = ^(BOOL silent){
      // do something
};

6.监听耳机拔插

监听AVAudioSessionRouteChangeNotification通知:

1
2
3
[[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(audioRouteChangeListenerCallback:)                                               name:AVAudioSessionRouteChangeNotification
                                          object:nil];

实现回调:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (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;
    }
}

Comments