游戏少不了背景音乐和音效。下面我们通过创建一个管理音效的类,来实现背景音乐的播放,同时点击屏幕可以播放相应的音效。
声音管理类 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(){
//获取apple.mp3文件地址
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 ) {
}
} |