Ask Your Question
0

What is the procedure for utilizing UIslider in iOs AVFoundation to establish the starting music volume at 50%?

asked 2022-12-06 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-08-07 03:00:00 +0000

plato gravatar image
  1. Create an instance of the AVAudioPlayer and set the desired music file URL.
  2. Set the initial volume of the AVAudioPlayer by calling setVolume method with the value of 0.5 (50%).
  3. Create a UISlider instance using the Interface Builder or programmatically.
  4. Set the minimum value of the UISlider to 0 and the maximum value to 1 (representing the range of volume values).
  5. Set the initial value of the UISlider to 0.5.
  6. Add an action method to the UISlider instance to handle changes in value.
  7. In the action method, access the AVAudioPlayer instance and set its volume to the value of the UISlider.
  8. Run the application and test the functionality.

Here is a sample code:

import AVFoundation
import UIKit

class ViewController: UIViewController {

    var audioPlayer: AVAudioPlayer!
    @IBOutlet var volumeSlider: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()

        let musicURL = Bundle.main.url(forResource: "music", withExtension: "mp3")!
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: musicURL)
            audioPlayer.prepareToPlay()
            audioPlayer.volume = 0.5
        } catch let error {
            print("Error: \(error.localizedDescription)")
        }

        volumeSlider.minimumValue = 0
        volumeSlider.maximumValue = 1
        volumeSlider.value = 0.5
        volumeSlider.addTarget(self, action: #selector(volumeChanged(_:)), for: .valueChanged)
    }

    @objc func volumeChanged(_ sender: UISlider) {
        audioPlayer.volume = sender.value
    }

    @IBAction func playButtonTapped(_ sender: AnyObject) {
        if !audioPlayer.isPlaying {
            audioPlayer.play()
        }
    }

    @IBAction func pauseButtonTapped(_ sender: AnyObject) {
        if audioPlayer.isPlaying {
            audioPlayer.pause()
        }
    }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-06 11:00:00 +0000

Seen: 7 times

Last updated: Aug 07 '22