2016-04-29 63 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) 

}