IOS音量调节--隐藏系统音量调节

有时候有这样的需求进入某个界面音量调节到到最大, 离开界面音量恢复到之前的大小

或者播放视频,音频文件时候将音量调节到最大, 播放完毕后恢复到原来的音量大小,程序控制改变  不显示系统音量调节的界面

这里写一下进入应用音量调节到最大, 退出应用之后, 音量恢复到之前的大小

在AppDelegate.m中导入#import

声明

@property (nonatomic, strong) MPVolumeView *volumeView;

方法: 记录当前音量, 并将音量调节到最大

- (void)monitorVolume
{
    //设置音量 为最大
    MPMusicPlayerController *musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
    NSNumber *nowVolum = [NSNumber numberWithFloat:musicPlayer.volume];
    NSLog(@"当前的音量是------%@",nowVolum);
    [[NSUserDefaults standardUserDefaults] setObject:nowVolum forKey:@"nowVolum"];
    
    //音量调节到最大
    [self setVolume:1.0f];
}
- (void)setVolume: (float)value
{
    if (!self.volumeView) {
        self.volumeView = [[MPVolumeView alloc] init];
        self.volumeView.frame = CGRectMake(0, 0, 200, 20);
        self.volumeView.center = CGPointMake(-550,370);
        [self.window addSubview:self.volumeView];
    }
    
    UISlider* volumeViewSlider = nil;
    for (UIView *view in [self.volumeView subviews]){
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            volumeViewSlider = (UISlider*)view;
            break;
        }
    }
    self.volumeView.showsVolumeSlider = NO;
    // change system volume, the value is between 0.0f and 1.0f
    [volumeViewSlider setValue:value animated:NO];
    // send UI control event to make the change effect right now.
    [volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
    [self.volumeView sizeToFit];
    
}

应用启动时候调节到最大

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self monitorVolume];
    return YES;
}

应用退出的时候恢复到之前的大小

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSNumber *oldVolume = [[NSUserDefaults standardUserDefaults] objectForKey:@"nowVolum"];
    [self setVolume:[oldVolume floatValue]];
}


你可能感兴趣的:(IOS开发)