可以使用AVAudioPlayer来播放声音文件,并使用它的delegate来实现在声音文件播放完毕时结束动画。具体步骤如下:
import AVFoundation
var audioPlayer: AVAudioPlayer?
func playSoundFile(named name: String) {
guard let url = Bundle.main.url(forResource: name, withExtension: "mp3") else { return }
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer?.numberOfLoops = 0
audioPlayer?.delegate = self
audioPlayer?.play()
} catch let error {
print(error.localizedDescription)
}
}
extension GameScene: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
// 结束动画的代码
}
}
通过这种方法,我们可以确保动画在每个声音文件播放完毕时自动结束,而无需手动定时每个声音文件。