按下音量按钮时更改音量滑块位置

时间:2017-06-27 10:28:41

标签: ios objective-c uislider

如何将音量按钮与音量滑块连接?

我正在使用AVAudioPlayer和滑块音量和物理音量按钮工作正常,但问题是它们是分开工作的,所以我需要实现的是当我按音量滑块按物理音量按钮时也改变位置。

我的代码如下:

-(IBAction)btnClked:(id)sender {

    NSURL *musicFile;

    musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                        pathForResource:@"music"
                                        ofType:@"mp3"]];

    myAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];

    [self.button setBackgroundImage:[UIImage imageNamed:@"Play.png"] forState:UIControlStateNormal];

    if (self.button.tag == 0) {
        self.button.tag = 1;
        [self.button setImage:[UIImage imageNamed:@"Stop.png"] forState:UIControlStateNormal];

        [myAudio play];
        myAudio.numberOfLoops = -1;
        myAudio.currentTime = 0;
        myAudio.volume = 0.5;

    } else {
        self.button.tag = 0;
        [self.button setImage:[UIImage imageNamed:@"Play.png"] forState:UIControlStateNormal];
        [myAudio stop];

    }
}

我的滑块更改方法如下所示:

- (IBAction)sliderChange:(UISlider *)sender {
    myAudio.volume = sender.value / 1;
}

提前致谢!

1 个答案:

答案 0 :(得分:0)

使用此MPVolumeView设置音量滑块您可以按自己的方式自定义...

- (void)showTheVolumeSlider :(UIView *)viewVolumeParent{

    MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:viewVolumeParent.bounds] ;
    volumeView.showsRouteButton = NO;
    [viewVolumeParent addSubview:volumeView];
//    [volumeView setVolumeThumbImage:[UIImage imageNamed:@"thumb.png"] forState:UIControlStateNormal];

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

            [obj setThumbImage:[UIImage imageNamed:@"thumb.png"]forState:UIControlStateNormal];
            *stop = YES;
        }
    }];
}