Get AVAudioPlayer to play multiple sounds at a time

前端 未结 4 407
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 17:44

I\'m trying to get multiple sounds files to play on an AVAudioPlayer instance, however when one sound plays, the other stops. I can\'t get more than one sound to play at a t

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 18:31

    All answers are posting pages of code; it doesn't need to be that complicated.

    // Create a new player for the sound; it doesn't matter which sound file this is
                    let soundPlayer = try AVAudioPlayer( contentsOf: url )
                    soundPlayer.numberOfLoops = 0
                    soundPlayer.volume = 1
                    soundPlayer.play()
                    soundPlayers.append( soundPlayer )
    
    // In an timer based loop or other callback such as display link, prune out players that are done, thus deallocating them
            checkSfx: for player in soundPlayers {
                if player.isPlaying { continue } else {
                    if let index = soundPlayers.index(of: player) {
                        soundPlayers.remove(at: index)
                        break checkSfx
                    }
                }
            }
    

提交回复
热议问题