1

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.

Sunny
  • 31
  • 5
  • I've just done this, two AVAudioPlayers were required, one for the music and another for the effects. https://stackoverflow.com/questions/36865233/get-avaudioplayer-to-play-multiple-sounds-at-a-time – StephenL Nov 06 '22 at 16:51

0 Answers0