我在Swift中有一个代码可以玩鸟类游戏。一只鸟收集鸡蛋。我想在鸟儿碰到鸡蛋时发出硬币声。我试过下面的代码,但它不是在接触时播放。我怎么能完成它?
do {
// Preperation
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch _ {
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
}
// Play the sound
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: alertSound)
} catch _{
}
audioPlayer.prepareToPlay()
audioPlayer.play()
答案 0 :(得分:1)
创建声音文件的路径
let path = NSBundle.mainBundle().pathForResource("(sound name)", ofType: (type) )!
路径的网址
var url = NSURL()
保持声音的变量
var soundEffect: AVAudioPlayer!
然后当你想播放声音时
url = NSURL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOfURL: url)
soundEffect = sound
sound.play()
} catch {
}