Scott Kilbourn
Scott Kilbourn

Reputation: 1586

Control volume of system sound

I have the following code for playing a click when a button is tapped.

private var clickSound: SystemSoundID!

clickSound = createSound("ButtonClick2", soundType: "wav")

AudioServicesPlaySystemSound(clickSound)

This sound plays at the same level, regardless of the volume on the device and whether the device is muted.

This is really two questions.

  1. How can I detect whether the device is muted? I want to not play the sound if the device is muted.
  2. How can I adjust the volume of the sound based on the volume of the device?

Upvotes: 0

Views: 2190

Answers (2)

Ram
Ram

Reputation: 979

You can get the System Volume

let volume = AVAudioSession.sharedInstance().outputVolume   
print("Output volume: \(volume)"

the value of volume is from 0.0 to 1.0

Upvotes: 1

Tim
Tim

Reputation: 2098

The reason this doesn't respond to user sound level is you created a system sound. Instead, use AVAudioPlayer.

do {
    let player = try AVAudioPlayer(contentsOf: soundFileURL)
    player.play()
} catch {
    print("Error")
}

Upvotes: 2

Related Questions