iOS 监听音量调节 事件

阅读更多
iOS 监听音量调节 事件

做项目需要音量调节的事件来控制其他动作,找了半天,调试了一下,一下代码都可以直接使用。经过测试的。
有两个方法:
方法一:
添加AudioToolbox.framework
Appdelegate.m中,添加头文件#include
在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中添加
    AudioSessionInitialize(NULL, NULL, NULL, NULL);

    AudioSessionSetActive(true);

    AudioSessionAddPropertyListener(kAudioSessionProperty_CurrentHardwareOutputVolume ,

                                    volumeListenerCallback,

                                    (__bridge void *)(self)

                                    );

外加回调函数



void volumeListenerCallback (

                             void                      *inClientData,

                             AudioSessionPropertyID    inID,

                             UInt32                    inDataSize,

                             const void                *inData

                             ){

    const float *volumePointer = inData;

    float volume = *volumePointer;

    NSLog(@"volumeListenerCallback %f", volume);

}

搞定。

方法二:较为简单实用

添加MediaPlayer.framework

在Appdelegate.m中

在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions方法中添加



    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(volumeChanged:)

                                             name:@"AVSystemController_SystemVolumeDidChangeNotification"

                                               object:nil];

然后添加方法



-(void)volumeChanged:(NSNotification *)noti

{                                  

    float volume =

    [[[noti userInfo]

      objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]

     floatValue];

    NSLog(@"volumn is %f", volume);

}

在controller.m中添加头文件#import

在Viewdidload中添加



    MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];

    volumeView.center = CGPointMake(150,370);

    [volumeView sizeToFit];

    [self.view addSubview:volumeView];

就搞定了

from:
http://blog.sina.com.cn/s/blog_65a8ab5d0101cb9k.html

你可能感兴趣的:(Objective-C,ios,Cocoa,Apple)