Answer the question
In order to leave comments, you need to log in
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
}
Answer the question
In order to leave comments, you need to log in
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
}
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 outputVolume
is 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 questionAsk a Question
731 491 924 answers to any question