【发布时间】:2018-12-28 19:06:41
【问题描述】:
对于我游戏中的背景音乐,我想播放两个声音。第一个声音在开始时只播放一次(4 小节介绍)。之后,第二个声音(主音乐)无限循环播放。不幸的是,下面的代码同时播放声音,而不是按顺序播放(当我查看 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
}
}
【问题讨论】:
-
"当我查看 AVQueuePlayer 时,我无法弄清楚如何只循环两个声音中的第二个" 不过,这是一个很好的方法。