在 Swift 中,如何让音乐在用户使用我的应用程序时继续播放? (快速用户界面)

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

当用户点击按钮时,它会播放音乐,然后停止播放背景音乐。但我想要的是背景音乐即使在用户点击按钮后也能继续播放

这是播放音乐的代码

@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 :(
        }

}

如何让背景音乐在用户点击此按钮后继续播放?

将下面的代码放在self.bombSoundEffect = try AVAudioPlayer(contentsOf: url)

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

为了可重用性,我发现创建一个 class 非常有用,可以避免在其他视图中重复代码。

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")
           }
        }
    }
}

然后像这样

通过Button在你的视图中使用它
Button("Play Sound") {
    Sounds.play(sound: "bombSoundEffect", type: "mp3") //Local file example
}