如何在iOS9中更改音量?

时间:2016-02-04 23:59:56

标签: ios objective-c uislider mpvolumeview

此代码在iOS 8.0设备中运行良好,但在iOS 9.0中,总是将滑块值设为0.000 ...

(void) volumeUp{

MPVolumeView * volumeView = [[MPVolumeView alloc] init];

//find the volumeSlider
UISlider* volumeViewSlider = nil;
for (UIView *view in [volumeView subviews]){
    if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
        volumeViewSlider = (UISlider*)view; // volumeViewSlider always 0.000
        break;
    }
}

[volumeViewSlider setValue: [volumeViewSlider value] + 0.0625 animated:YES];
[volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];

}

我该如何解决?我需要每次调高音量0.0625。

谢谢!

1 个答案:

答案 0 :(得分:0)

在您的代码中,当您调用volumeUp时,它会创建一个新的MPVolumeView并返回0或其他内容。但是如果您创建一个MPVolumeView并按属性保存它,它将提供您想要的内容。

像这样:

@interface ViewController ()
@property (strong, nonatomic) MPVolumeView *volumeView;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    MPVolumeView *vv = [[MPVolumeView alloc] init];
    self.volumeView = vv;
}

- (IBAction)volumeUp:(id)sender
{
    //find the volumeSlider
    UISlider* volumeViewSlider = nil;
    for (UIView *view in [self.volumeView subviews]){
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            volumeViewSlider = (UISlider*)view; // volumeViewSlider always 0.000
            break;
        }
    }

    [volumeViewSlider setValue: [volumeViewSlider value] + 0.0625 animated:YES];
    [volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
}