1. 程式人生 > >iOS 監聽和設定系統音量

iOS 監聽和設定系統音量

一:監聽系統音量

1:新增 #import <AVFoundation/AVFoundation.h>

2:在 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 新增

 //監聽系統聲音

    AVAudioSession *session = [AVAudioSession sharedInstance];

    [session setCategory:AVAudioSessionCategoryAmbient error:nil];//重點方法

    [session setActive:YES error:nil];

    NSError *error;

    [[AVAudioSession sharedInstance] setActive:YES error:&error];

    //注,ios9上不加這一句會無效

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

3:在需要新增監聽的地方監聽音量

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];

//系統聲音改變

-(void)volumeChanged:(NSNotification *)notification

{

    float volume = [[[notification userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];

    NSLog(@"FlyElephant-系統音量:%f", volume);

}

 二:設定系統音量

#import <MediaPlayer/MediaPlayer.h>

 //初步同步系統的音量跟耳機初步音量達成一致

        MPVolumeView *volumeView = [MPVolumeView new];

        volumeView.showsRouteButton = NO;

        volumeView.showsVolumeSlider = NO;

        [self.view addSubview:volumeView];

       // __weak __typeof(self)weakSelf = self;

        [[volumeView subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

            if ([obj isKindOfClass:[UISlider class]]) {

                //__strong __typeof(weakSelf)strongSelf = weakSelf;

                volumeViewSlider = obj;//UISlider* volumeViewSlider;

                *stop = YES;

            }

        }];

        [volumeViewSlider setValue:volumeF animated:YES];