iOS 声音按键的监听

一、 添加两个框架 :MediaPlayer.framework和AudioToolbox.framework

 

  1. 添加两个头文件

#import <MediaPlayer/MediaPlayer.h>

#import <AudioToolbox/AudioToolbox.h>

 

 

  1. 添加通知

一般在程序刚刚启动的时候添加:- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

 

 

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

}

实现监听的方法:

- (void) volumeChanged:(NSNotification *) notification

{

    

    // 获取当前系统音量的值范围是0.0-1.0,是一个浮点型

    float volume =

    [[[notification userInfo]

      objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]

     floatValue];

    

    

    NSLog(@"----音量:%f-------",volume);

    if (!self.isMuted && volume < self.volume) {

        [[MPMusicPlayerController applicationMusicPlayer] setVolume:0.0];

    } else if (volume > self.volume){

        [[MPMusicPlayerController applicationMusicPlayer] setVolume:volume];

    }

    self.volume = volume;

    

    

 

}

 

// 判断是否静音(一般定义一个全局变量,在其getter方法里实现)

 

- (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) dealloc

{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];

 

}

posted @ 2015-04-29 18:20  pocket_live  阅读(213)  评论(0编辑  收藏  举报