如何用音频播放器同时播放两个声音?

编程语言 2026-07-09

我拿到了这段代码,用来在我的第一款游戏中播放声音:

class SoundManager {


    func playSoundEffect(sound:String, model:Model) {

        if model.soundMuted == false {

            switch(sound) {
            case "swoosh":
                self.playTheSound("Swoosh", "mp3")
            case "key tap":
                self.playTheSound("Key Tap", "mp3")
            default:
                break
            }
        }
    }



    func playTheSound(_ soundName:String, _ soundType:String) {
        SoundManager.shared.configureAudioSession()
        SoundManager.shared.playSound(sound: soundName, type: soundType)
    }




    static let shared = SoundManager()
    var audioPlayer: AVAudioPlayer?
    var audioPlayer2: 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()


                if audioPlayer?.isPlaying == false {

                    audioPlayer?.play()


                } else if audioPlayer?.isPlaying == true {

                    audioPlayer2 = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                    audioPlayer2?.play()
                }


            } catch {
                print("ERROR: Could not find and play the sound file.")
            }
        }
    }



    func configureAudioSession() {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, options: [.mixWithOthers])
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print("Failed to set audio session category: \(error.localizedDescription)")
        }
    }


}

所以在我的游戏中,我会这样调用声音:

soundManager.playSoundEffect(sound: "swoosh", model: model)

我需要同时播放不止一个声音,但在我看来,每次调用声音时它似乎都会创建一个全新的音频播放器。因此,我不确定如何检查音频播放器是否正在播放("isPlaying")。

也看不到如何添加一个监听器来查看音频何时停止播放(如果是那样,我可以创建一个isPlaying的布尔变量,在音频播放器结束时切换它。)

解决方案

Looking at your code it seems like your audioPlayer instance is getting override. Hence you see new instance every time. What you can do is create audioPlayer array and append player instance into it. This will make full proof like you can create n number of audioPlayer instance and play multiple sounds accordingly for instance :-

var players: [AVAudioPlayer] = []

func playYourSound(name: String) {
    guard let url = Bundle.main.url(forResource: name, withExtension: "mp3") else { return }

    let player = try! AVAudioPlayer(contentsOf: url)
    player.play()

    players.append(player)

    // Just for filtering. This is needed to remove the instance once sounds stopped and avoid retaining redundant instance of audioPlayer
    players = players.filter { $0.isPlaying }
}

playYourSound(name: "sound1")
playYourSound(name: "sound2")
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章