我正试图在游戏菜单中播放随机声音,它实际上是鸟类在偷窥。 所以有很多鸟的声音,但我希望它们是随机的。
我之前使用schedule
执行此操作的方式如下:
this->schedule(schedule_selector(HelloWorld::birdsound),3.2);
其中:
void HelloWorld::birdsound(){
int soundnum=arc4random()%9+1;
switch (soundnum) {
case 1:
appdelegate->bird1();
break;
case 2:
appdelegate->bird2();
break;
.
.
.
case 9:
appdelegate->bird9();
break;
default:
break;
}
}
因此,播放随机声音,例如bird1()
:
void AppDelegate::bird1(){
CocosDenshion::SimpleAudioEngine::sharedEngine()->stopAllEffects();
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("bird1.mp3");
}
我怎样才能在Spritekit / swift中实现类似的东西,我可以以随机的顺序发送X
量的声音文件(或鸟类泣叫),中间有一个小的间隙(或等待)?可以使用SKActions
完成吗?
答案 0 :(得分:0)
您可以做的是将声音文件放入数组,设置音频播放器,然后创建一个随机播放声音的功能。然后使用一个计时器,在你想要的任何时间间隔调用该函数。所以:
Class GameScene {
var soundFiles = ["bird_sound1", "bird_sound2"]
var audioPlayer: AVAudioPlayer = AVAudioPlayer()
func setupAudioPlayer(file: NSString, type: NSString){
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
}
catch {
print("Player not available")
}
}
func playRandomSound() {
let range: UInt32 = UInt32(soundFiles.count)
let number = Int(arc4random_uniform(range))
self.setupAudioPlayer(soundFiles[number], type: "wav")
self.audioPlayer.play()
}
override func didMoveToView(view: SKView) {
_ = NSTimer.scheduledTimerWithTimeInterval(7, target: self, selector: #selector(GameScene.playRandomSound), userInfo: nil, repeats: true)
}
答案 1 :(得分:0)
使用SKAction
我实现了这样:
加载声音:
let cheep1 = SKAction.playSoundFileNamed("bird1.mp3", waitForCompletion: false)
//and so on
创建一个等待时间并永远调用序列:
func beginRandomCheeping(){
let sequence = (SKAction.sequence([
SKAction.waitForDuration(2.0),
SKAction.runBlock(self.playRandomSound)
]))
let repeatThis = SKAction.repeatActionForever(sequence)
runAction(repeatThis)
}
随机声音和播放:
func playRandomSound() {
let number = Int(arc4random_uniform(UInt32(9)))
switch (number){
case 1:
runAction(cheep1)
break
case 2:
runAction(cheep2)
break
.
.
.
case 9:
runAction(cheep9)
break
default:
break
}
}
只需在游戏逻辑中的某处调用self. beginRandomCheeping()
。