---
title: "iOS 监听音量调节 事件"
author: "bengan"
date: "2013-08-14T12:18:47Z"
tags: ["Apple", "Cocoa", "Objective-C", "iOS"]
categories: ["移动开发"]
slug: "ios"
draft: false
lastmod: "2013-08-14T12:18:47Z"
id: 1924395
url: "https://bengan.iteye.com/blog/1924395"
---

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