对于游戏中的背景音乐,我想播放两种声音。第一个声音在开始时只播放一次(4 bar前奏)。之后,第二个声音(主要音乐)循环播放。不幸的是,下面的代码同时播放声音,而不是顺序播放(当我查看AVQueuePlayer时,我无法弄清楚如何仅循环播放两种声音中的第二种):
var backgroundMusicPlayer: AVAudioPlayer!
var backgroundMusicPlayerIntro: AVAudioPlayer!
func playBackgroundMusic(filename: String, withIntro intro: String) {
let resourceUrl = Bundle.main.url(forResource: filename, withExtension: nil)
let resourceUrlIntro = Bundle.main.url(forResource: intro, withExtension: nil)
guard let url = resourceUrl, let urlIntro = resourceUrlIntro else {
print("Could not find files: \(intro) and/or \(filename)")
return
}
//play the intro first before playing the main loop
do {
try backgroundMusicPlayerIntro = AVAudioPlayer(contentsOf: urlIntro)
backgroundMusicPlayerIntro.numberOfLoops = 1
backgroundMusicPlayerIntro.prepareToPlay()
backgroundMusicPlayerIntro.play()
} catch {
print("Could not create audio player!")
return
}
//main music that gets played on repeat
do {
try backgroundMusicPlayer = AVAudioPlayer(contentsOf: url)
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
} catch {
print("Could not create audio player!")
return
}
}
答案 0 :(得分:0)
您同时启动2位玩家。您可以使用一个播放器属性,并且在第一个声音的末尾调用AVAudioPlayerDelegate
方法时,audioPlayerDidFinishPlaying
可以播放第二个声音。基本上是这样的:
class Player: AVAudioPlayerDelegate {
var audioPlayer: AVAudioPlayer?
func startPlayingFirstSong() {
// your 1st do/catch code...
try audioPlayer = AVAudioPlayer(contentsOf: urlIntro)
audioPlayer?.delegate = self
}
// AVAudioPlayer will call this func when the first song ends:
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
// your 2nd do/catch code...
try audioPlayer = AVAudioPlayer(contentsOf: url)
audioPlayer?.delegate = self
}
}
let player = Player()
player.startPlayingFirstSong()