Search code examples
swiftaudiotoolbox

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?

Solution

  • 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")
    }