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];

     

    }

  • 相关阅读:
    CentOS离线状态下安装Python3.7.0
    SQL练习题
    ajax的工作原理
    总结 XSS 与 CSRF 两种跨站攻击
    转css中文英文换行、禁止换行、显示省略号
    vue项目的搭建
    转axios 的应用
    rem布局计算(移动端,pc端有兼容性)
    rem
    彻底弄懂css中单位px和em,rem的区别
  • 原文地址:https://www.cnblogs.com/pocket-mood/p/4466735.html
Copyright © 2011-2022 走看看