Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Volume Slider in swift

I am trying to create a slider that controls volume of 4 audio files.

Here is my code for the audio:

var ButtonAudioURL  = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("audio1", ofType: "mp3")!)

var firstplayer     = AVAudioPlayer()    
var ButtonAudioURL2 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("audio2", ofType: "mp3")!) 

var secondplayer   = AVAudioPlayer()    
var ButtonAudioURL3 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("audio3", ofType: "mp3")!)

var thirdplayer = AVAudioPlayer()    
var ButtonAudioURL4 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("audio4", ofType: "mp3")!)

var forthplayer = AVAudioPlayer()

override func viewDidLoad() {

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    firstplayer  = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error: nil)        
    secondplayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL2, error: nil)     
    thirdplayer  = AVAudioPlayer(contentsOfURL: ButtonAudioURL3, error: nil)       
    forthplayer  = AVAudioPlayer(contentsOfURL: ButtonAudioURL4, error: nil)

I have the audio to play when each button is touched. But I just need to get a slider to control the volume of each audio file from each button.

How should i do this? I have looked at MPVolumeView class reference on developer.apple, but I am still confused and in the developer.apple reference for MPVolumeView, it talks about AirPlay, can I disable that?

I just need a slider to control the volume.

like image 983
foxcowz Avatar asked Oct 25 '25 04:10

foxcowz


2 Answers

If you use Swift 2 Try with this:

@IBOutlet weak var volumen: UISlider!
var reproductor = AVAudioPlayer()

after:

    @IBAction func sliderValueChanged(sender: UISlider) {

    let selectedValue = Float(sender.value)
    reproductor.volume = selectedValue

}

and try your slider volume during the playing sound. That is all. I've helped.

like image 123
gandhi Mena Avatar answered Oct 26 '25 18:10

gandhi Mena


You're close!

Drag in a slider into your storyboard, and create an IB outlet and IB action for it.

In the IB action code, use firstPlayer.volume = sliderOutlet.value

Since both range from 0 to 1 as default, they are on the same scale and so can be used like this without scaling. You may need to declare the AVAudioPlayers more globally and have a way of seeing which button was pressed (e.g. a variable that stores the name of the button pressed). That way, you change the correct volume using 4 if statements and don't end up changing the volume for a player that has not been initialized yet.

Let me know if this works!

like image 20
Baptiste Bouvier Avatar answered Oct 26 '25 17:10

Baptiste Bouvier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!