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

     

    }

  • 相关阅读:
    datatable转json
    GridView 自定义表头
    jquery之each
    验证码
    C# 添加,修改,删除文件夹/文件集合
    SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
    bootstrap 简易模版
    容易上手-类似ERP系统 简单特效
    定义文字样式-插件
    获取当前url并指定url中的字符 效果
  • 原文地址:https://www.cnblogs.com/pocket-mood/p/4466735.html
Copyright © 2011-2022 走看看