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?