首先包含这两个头文件以及加入对应的框架
#import <MediaPlayer/MediaPlayer.h>
#import <AudioToolbox/AudioToolbox.h>
添加声音通知的监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
// 获取当前系统音量
self.volume = [[MPMusicPlayerController applicationMusicPlayer] volume];
// 判断是否静音
- (BOOL) isMuted
{
CFStringRef route;
UInt32 routeSize = sizeof(CFStringRef);
OSStatus status = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &routeSize, &route);
if (status == kAudioSessionNoError)
{
if (route == NULL || !CFStringGetLength(route))
return TRUE;
}
return FALSE;
}
// 声音通知监听的实现
- (void) volumeChanged:(NSNotification *) notification
{
// 获取当前声音的值
float volume =
[[[notification userInfo]
objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]
floatValue];
// NSLog(@"现在音量:%f",volume);
if (!self.isMuted && volume < self.volume && self.acceptBtn.hidden == NO) {
// 设置音量为静音
[[MPMusicPlayerController applicationMusicPlayer] setVolume:0.0];
// 添加系统震动
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
NSLog(@"----isMuted音量:%f-------",volume);
} else if (volume > self.volume && self.acceptBtn.hidden == NO){
[[MPMusicPlayerController applicationMusicPlayer] setVolume:volume];
NSLog(@"----!isMuted音量:%f-------",volume);
}
// 更新记录音量值的变量
self.volume = volume;
}