Swiftui - Play background music with other sound effects and toggle audio button

Viewed 24

I have following Code for Audio Player in SwiftUI.

import AVFoundation

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?.play()
    } catch {
      print("ERROR: Could not find and play the sound file!")
    }
  }
}

To Play the sound in Content view its called as.

playSound(sound: "filename", type: "mp3")

Issue is. I add background music mp3. It works fine. But now I assign a click button sound using same command, which stops the background music,

How can I continue playing the background music along with other one off sound effects. As a bonus how can I create a button which mute/unmute background music within the app.

Thank you so much.

0 Answers
Related