游戏少不了背景音乐和音效。下面我们通过创建一个管理音效的类,来实现背景音乐的播放,同时点击屏幕可以播放相应的音效。
声音管理类 SoundManager.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import SpriteKit
import AVFoundation
class SoundManager : SKNode {
var bgMusicPlayer = AVAudioPlayer ()
let hitAct = SKAction .playSoundFileNamed( "hit.mp3" , waitForCompletion: false )
func playBackGround(){
var bgMusicURL: NSURL = NSBundle .mainBundle(). URLForResource ( "bg" , withExtension: "mp3" )!
bgMusicPlayer= AVAudioPlayer (contentsOfURL: bgMusicURL, error: nil )
bgMusicPlayer.numberOfLoops = -1
bgMusicPlayer.prepareToPlay()
bgMusicPlayer.play()
}
func playHit(){
self .runAction(hitAct)
}
}
|
主场景 SoundManager.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import SpriteKit
class GameScene : SKScene {
lazy var sound = SoundManager ()
override func didMoveToView(view: SKView ) {
self .addChild(sound)
sound.playBackGround()
}
override func touchesBegan(touches: NSSet , withEvent event: UIEvent ) {
sound.playHit()
}
override func update(currentTime: CFTimeInterval ) {
}
}
|