2016-04-29 64 views
1

我试图在游戏菜单中播放随机声音,它实际上是鸟儿在吱吱作​​响。 所以有很多鸟的声音,但我希望他们是随机的。在SpriteKit中安排音频 - Swift

我以前做过这个使用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

使用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()

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) 

}