iOS 静音模式下播放视频、音乐和控制音量大小

1、允许静音模式下播放声音

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:nil]; 

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

- (void)dealloc {    

        [[UIApplication sharedApplication] endReceivingRemoteControlEvents]; 

} }

2、实现声音控制

@property (nonatomic, strong)MPVolumeView *volumeView;

@property (nonatomic, strong)UISlider *volumeSlider;

[[AVAudioSession sharedInstance]outputVolume];         

MPMusicPlayerController *musicPlayer = [MPMusicPlayerController applicationMusicPlayer];    

if (([musicPlayer respondsToSelector:@selector(setVolume:)]) && [[[UIDevice currentDevice] systemVersion] floatValue] >= 13.0) {        

//消除警告

#pragma clang diagnostic push

#pragma clang diagnostic ignored "-Wdeprecated-declarations"        

    if ([self getVolume] == 0) {

            [musicPlayer setVolume:0.5];        

        }

#pragma clang diagnostic pop   

}else {        

// 低版本按照正常的设置依然不能控制音量  故使用了MPMusicPlayerController        

if ([self getVolume] == 0) {

           [musicPlayer setVolume:0.5];        

    }    

}

- (MPVolumeView *)volumeView {

    if (!_volumeView) {

        _volumeView = [[MPVolumeView alloc] initWithFrame:CGRectZero];

        // 将x、y设置成 -100 就会将音量界面隐藏

        // 下面两行代码都会使音量界面重新显示

         [_volumeView setHidden:YES];

         [_volumeView removeFromSuperview];

        [self.view addSubview:_volumeView];

    }

    return _volumeView;

}

- (UISlider*)volumeSlider {

    UISlider* volumeSlider =nil;

    for(UIView*view in[self.volumeView subviews]) {

        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){

            volumeSlider = (UISlider*)view;

            break;

        }

    }

    return volumeSlider;

}

- (float)getVolume {

    return self.volumeSlider.value > 0 ? self.volumeSlider.value : [[AVAudioSession sharedInstance] outputVolume];

}

这样  简单的静音模式下播放声音就实现了   内容可根据自身情况进行更改。demo地址

你可能感兴趣的:(iOS 静音模式下播放视频、音乐和控制音量大小)