0%

视频播放 Tips

获取设备音量

播放音频可以通过:

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

播放视频可以通过:

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

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

静音模式失效

通过设置音频会话的 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 就不会随着手机静音键打开而静音,可在手机静音下播放声音😁

监听音量改变

监听音频改变私有通知:

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
}

设置设备音量

使用 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;

监听静音按钮

参考Sound Switch - Sharkfood的实现。

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

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

动态监听,通过 block 回调:

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

监听耳机拔插

监听 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;
}
}