Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  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()
        }
    }
}