2

I'm looking to add a sound to a button in my SwiftUI project.

I want the sound volume to be always the same, and not depending on the system main volume. Meaning, that when the user click on the button, he will always hear the sound with the same volume level (except if the device is on silent mode)

Here is my code:

var audioPlayer: AVAudioPlayer?
func playSound(sound: String, type: String)  {
    if let path = Bundle.main.path(forResource: sound, ofType: type) {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
            audioPlayer?.setVolume(0.01, fadeDuration: 0.1)
            audioPlayer?.play()
        } catch {
            print("Sound file not found")
        }
    }
}

And I call it like this:

Button(action: {
    print("button pressed")
    playSound(sound: "sound4", type: "mp3")
}) {
    Image(systemName: "heart")
}

The problem with this is that it's reducing the volume depending on the system main volume, which is not exactly what I'm looking for.

Any solution?

aheze
  • 24,434
  • 8
  • 68
  • 125
Theoutsider
  • 63
  • 1
  • 7
  • 2
    I think this is how it was designed to be. You can set the system volume [like this](https://stackoverflow.com/a/36323079/14351818) though – aheze Apr 22 '21 at 15:38
  • I see . But is there any solution to avoid cutting the main sound when tapping on the button? I mean, the user will not her the sound of the button if the user is for example listening to music. The problem I'm facing now is that tapping on the button will also stop any sound coming from any other app – Theoutsider Apr 22 '21 at 20:31
  • 1
    Look into AVAudioSession category options (especially `mixWithOthers` and `duckOthers`): https://developer.apple.com/documentation/avfaudio/avaudiosession/categoryoptions – jnpdx Apr 22 '21 at 20:38
  • thanks, just have to add this and then everything works perfect – Theoutsider Apr 22 '21 at 21:06

0 Answers0