zoukankan      html  css  js  c++  java
  • 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];

     

    }

  • 相关阅读:
    编译和和运行amor
    用好C语言的中库,系统错误的处理
    C语言中的宏
    时隔多年,再次实现的链表
    脚本更改桌面背景
    python爬虫 一个security的RSA加密爬虫
    mysql 8.0版本
    mysql5.7的并行复制
    kinshard中间件问题
    Springboot2-@Transactional 事务不生效
  • 原文地址:https://www.cnblogs.com/pocket-mood/p/4466735.html
Copyright © 2011-2022 走看看