S
S
Stanislav2018-11-10 13:10:31
Swift
Stanislav, 2018-11-10 13:10:31

How to access current iPhone volume and display it in your app in swift?

Hello.
Is it possible, when developing applications in swift for iOS, to get access to the current volume level of the phone and display it in the player?
So far I'm using a variant in AVPlayer:

@IBAction func handleVolumeChange(_ sender: UISlider) {
        player.volume = sender.value
    }

with the preset level of the maximum UISlider parameter, in my case 1, by moving the slider everything works and the volume changes, but the initial volume is 1, and not the current volume of the audio playback of the iPhone itself. If you turn on the system applications Music or Podcasts, there the volume slider level always corresponds to the current volume level of the audio playback of the iPhone itself.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dima Grib, 2018-11-10
@YeahGarage

The best way so
This is for you edited, from the game implementation

let audioFiles: [String: String] = [
        "": "",
        "": "",
        "": "",
        "":"",
        ]
    
    var players : [AVAudioPlayer] = []
    var volume = 0.0
    
//    init () {
//        for (name, ext) in audioFiles {
//            let a1 = setupAudioPlayerWithFile(file: name as NSString, type:ext as NSString)
//            players.append(a1!)
//        }
//    }
//
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
    
    func setVolume(v:Double) {
        volume = v
        for audioPlayer in players {
            audioPlayer.volume = Float(volume)
        }
    }
    
    func playSound(i:Int)
    {
        let audioPlayer = players[i]
        audioPlayer.play()
    }
    
    func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer?  {
        let path = Bundle.main.path(forResource: file as String, ofType: type as String)
        let url = NSURL.fileURL(withPath: path!)
        var audioPlayer:AVAudioPlayer?
        do {
            try audioPlayer = AVAudioPlayer(contentsOf: url)
            audioPlayer!.prepareToPlay()
            
        } catch {
            print("Player not available")
        }
        return audioPlayer
    }

M
Mikhail Lysenko, 2018-11-20
@mixei-ml

The notifications described here did not work for me, so I used the timer just to show the work. Look for system notifications so that the work is adequate.
If you don't activate the session, then the value outputVolumeis always 0.5, so don't forget to do this:

do {
    try AVAudioSession.sharedInstance().setActive(true, options: [])
} catch {
    print(error)
}

Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) {(timer) in
    print(AVAudioSession.sharedInstance().outputVolume)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question