Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift, How can I make music keep playing while user is using my app? (swiftUI)

When a user taps the button, it plays the music, and then it stops background music playing. But what I want is background music to keep playing even after the user had tapped the button

Here is code for playing the music

@State var bombSoundEffect: AVAudioPlayer?




Button("Button") {
 let path = Bundle.main.path(forResource: "example.mp3", ofType:nil)!
            let url = URL(fileURLWithPath: path)


        do {
            self.bombSoundEffect = try AVAudioPlayer(contentsOf: url)
            self.bombSoundEffect?.play()
        } catch {
            // couldn't load file :(
        }

}

How can I make background music keep playing even after user taps this button?

like image 490
Seungjun Avatar asked Oct 16 '25 04:10

Seungjun


1 Answers

Put the below code before self.bombSoundEffect = try AVAudioPlayer(contentsOf: url)

_ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: .mixWithOthers)

For reusability I found that creating a class is quite helpful in order to not repeat code in other views.

class Sounds {
    static var audioPlayer: AVAudioPlayer!

    static func play(sound: String, type: String) {
        if let path = Bundle.main.path(forResource: sound, ofType: type) {
           do {
               //Doesn't stop background music
               _ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: .mixWithOthers)
               //Load & play sound
               audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
               audioPlayer?.play()
           } catch {
               print("Error playing sound")
           }
        }
    }
}

Then just use it in your view via a Button like so

Button("Play Sound") {
    Sounds.play(sound: "bombSoundEffect", type: "mp3") //Local file example
}
like image 120
JLively Avatar answered Oct 17 '25 20:10

JLively