首先包含這兩個頭文件以及加入對應的框架app
#import <MediaPlayer/MediaPlayer.h>框架
#import <AudioToolbox/AudioToolbox.h>spa
添加聲音通知的監聽server
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];io
// 獲取當前系統音量class
self.volume = [[MPMusicPlayerController applicationMusicPlayer] volume];import
// 判斷是否靜音變量
- (BOOL) isMutedobject
{route
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;
}