Mi Ch Mi Ch - 3 months ago 12x
Swift Question

How to implement sender.selected if statement into UISlider?

I am trying to create a slider that changes audio dependent on the value of the slider. So, for example, if the slider value is 0, no audio plays. If the value is 1, 'song a' plays and if the value is 2, 'song b' plays etc.

I am using AVFoundation and have created my soundplayer:

var soundPlayer:AVAudioPlayer = AVAudioPlayer()

I have added outlets to my slider:

@IBOutlet weak var audioSlider: UISlider!
@IBOutlet weak var audioSliderPlay: UISlider!

Defined the file location of my audio:

let audioLocation = NSBundle.mainBundle().pathForResource("song a", ofType: ".mp3")

Created a do method for my player:

do {
audioSoundPlayer = try AVAudioPlayer (contentsOfURL: NSURL (fileURLWithPath: audioLocation!))
catch {

And created my action:

@IBAction func audioSlider(sender: UISlider) {
if (!sender.selected) {
audioSoundPlayer.numberOfLoops = -1

Now - the slider currently activates song a when any value is chosen. Once the audio has started, it cannot be stopped. I need to add a sender.value and create variables that define the value and choose other songs that I am going to add.

Help please?!

Edit with Amit issue:

Amit - I have changed the maximum value of the slider to 3 for 3 audios.

On adding the following to the IBAction, the slider only plays one audio once it reaches the maximum value:

@IBAction func audioSlider(sender: UISlider) {
let sliderValue = (sender.value)
if sliderValue == 1 {
soundPlayer1.numberOfLoops = -1

else if sliderValue == 2 {
soundPlayer2.numberOfLoops = -1

else if sliderValue == 3 {
soundPlayer3.numberOfLoops = -1

else if sliderValue == 0 {


You slider's value property as sender.value as typecast it to Int and change the audio according to your need.

You do need to set the minimum and maximum value of the slider before using it.

Set default to 0, minimum to 0 and maximum to your need or number of songs you have.

You can use the "pattern-match" operator ~=:

let sliderValue = Int(slider.value)

if 100 ... 199 ~= sliderValue {
    print("play audio 1")
else if 200 ... 299 ~= sliderValue {
    print("play audio 2")