SwiftUI 出现 AVAudioPlayer 多次播放

SwiftUI on appear AVAudioPlayer plays multiple times

我正在尝试为我的应用程序添加背景音乐的 AVAudioPlayer,我在主屏幕上启动播放器,试图在应用程序打开时开始播放但出现意外行为...
它播放并立即不断地创建新玩家并播放这些玩家,因此同时播放数十个相同的声音

音乐的启动和播放功能

if let path = Bundle.main.path(forResource: sound, ofType: type) {
    do {
        backgroundPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
        backgroundPlayer?.play()
    } catch {
        print("BACKGROUND MUSIC ERROR")
    }
}

出现时调用函数
.onAppear {
    audioController.backgroundMusic(sound: "bg", type: "wav")
}

编辑:示例代码...

import SwiftUI
import AVKit

struct ContentView: View {
    @ObservedObject var audioController = AudioController()

    var body: some View {
         Text("Hello, world!")
             .onAppear {
                 audioController.playBackgroundMusic(sound: "bg", type: "wav")
             }
    }
}

class AudioController: ObservableObject {
     var player: AVAudioPlayer?    

     func playBackgroundMusic(sound: String, type: String) {
        if let path = Bundle.main.path(forResource: sound, ofType: type) {
            do {
                player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                player?.play()
            } catch {
                print("BACKGROUND MUSIC ERROR")
            }
        }
    }
}

你可以尝试这样的事情:

func playBackgroundMusic(sound: String, type: String) {
    if !(player?.isPlaying ?? false) {
        if let path = Bundle.main.path(forResource: sound, ofType: type) {
            do {
                player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                player?.play()
            } catch {
                print("BACKGROUND MUSIC ERROR")
            }
        }
    }
}

发现它实际上只是一个“模拟器”错误,当应用程序从 xcode 构建中打开时,它会一遍又一遍地播放声音......但是在关闭并重新打开应用程序后,声音按预期播放。