coding22 coding22 - 7 months ago 9
Swift Question

How come music volume is not playing when my slider thumb is in the middle?

I have this UISlider that controls the volume of the music playing. When the thumb is in the middle the volume of the music is set to 1 and should play. The problem Im having is that its playing but once I move the thumb to the right or left and try to move the thumb back to the middle I cant hear any music. It works when I go to the left or right and plays the music for either AVPlayer except when the slider is in the middle. Thank you in advance!

middleSlider = UISlider(frame: CGRectMake(110 * scaleFactor, 50, 300, 150))
middleSlider.tintColor = UIColor.whiteColor()
middleSlider.setThumbImage(UIImage(named: "thumb3"), forState: UIControlState.Normal)
middleSlider.minimumTrackTintColor = UIColor.whiteColor()
middleSlider.maximumTrackTintColor = UIColor.whiteColor()
middleSlider.maximumValue = 2.0
middleSlider.minimumValue = 0.0
middleSlider.value = 1.0
middleSlider.continuous = true
middleSlider.userInteractionEnabled = false
middleSlider.addTarget(self, action: #selector(middleSliderChangeAudio), forControlEvents: UIControlEvents.AllEvents)
self.view?.addSubview(middleSlider)


func middleSliderChangeAudio() {
if middleSlider.value < 1.0 {

player.volume = 1
player2.volume = 0

}

if middleSlider.value > 1.0 {
player.volume = 0
player2.volume = 1
}

if middleSlider.value == 1.0 {
player.volume = 1
player2.volume = 1
}

}

Answer

Your app is implementing a really unfriendly UI. You are checking if the slider's knob is precisely in the center.

Even in the best case, this will be extremely difficult for anybody to do. There is exactly one pixel that the user will have to hit.

Also, depending on the frame of the slider, it may or may not be possible for the user to put the knob there, since the knob position will be adjusted to the nearest pixel. It may be impossible to exactly hit 1.0 -- the nearest possible positions could be slightly above and below 1.0.

Instead of checking for 1.0 exactly, you should look for values within some threshold of 1.0.

let threshold: Float = 0.05  // Experiment with this to see what feels best.
let lowerBoundary: Float = 1.0 - threshold
let upperBoundary: Float = 1.0 + threshold

if middleSlider.value < lowerBoundary {
    player.volume = 1
    player2.volume = 0
}
else if middleSlider.value <= upperBoundary {
    player.volume = 1
    player2.volume = 1
}
else /* must be middleSlider.value > upperBoundary */ {
    player.volume = 0
    player2.volume = 1
}

If you want to see the slider "snap" to the center, call middleSlider.value = 1.0 inside the middle condition.