AVAudioPlayer仅在第二次播放时循环播放

时间:2018-07-12 23:08:44

标签: ios avaudioplayer

我试图在玩家得分较高的情况下使用循环播放比分声音,然后通过循环播放两次奖励声音。乐谱声音始终正确播放。但是,第一次发生时,奖励声音只播放一次。之后,它会正确循环并播放两次。代码如下

var bonusSound:AVAudioPlayer = AVAudioPlayer()
var scoreSound:AVAudioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()
    loadAVPlayers()
}

func loadAVPlayers() {
    bonusSound = loadAVAudioPlayerFile(fileName: "Bonus sound", type: "m4a", volume: 0.5)!
    scoreSound = loadAVAudioPlayerFile(fileName: "Score sound", type: "m4a", volume: 0.5)!
    }

func loadAVAudioPlayerFile(fileName: String, type: String, volume: Float) -> AVAudioPlayer? {

    let fileURL = Bundle.main.url(forResource: fileName, withExtension: type)
    let newPlayer = try? AVAudioPlayer.init(contentsOf: fileURL!)
    newPlayer?.pan = +0.0
    newPlayer?.volume = volume
    newPlayer?.prepareToPlay()
    return newPlayer
}

@IBAction func playingScoringSounds(_ sender: UIButton) {

    //  Play the scoring and bonus sounds
    //  Score sound plays once.  Always works
    scoreSound.play()

    let soundTime = self.bonusSound.deviceCurrentTime + scoreSound.duration
    //  Bonus sound should play twice.  Only works the second time this function is called.
    bonusSound.numberOfLoops = 1
    bonusSound.play(atTime: soundTime)
}

我没有尝试解决此问题。谢谢。

0 个答案:

没有答案