2017-06-18 33 views
1

我試圖建立一個倒數計時器,併爲每個計數我想播放聲音。動畫工作正常,但我想知道如果我可以在按順序運行動畫時播放聲音。如何在運行動畫序列時添加副作用(播放聲音)?

CODE:

Animated.sequence([ 

      Animated.timing(this.state.moveY3, { 
       toValue: 50, 
       duration: 1000, 
       useNativeDrive: true, 
       easing: Easing.spring 
      }), // play sound 

      Animated.timing(this.state.moveY3, { 
       toValue: 100, 
       duration: 100, 
       useNativeDrive: true, 
      }), 

      Animated.timing(this.state.moveY2, { 
       toValue: 50, 
       duration: 1000, 
       useNativeDrive: true, 
       easing: Easing.spring 
      }), //play sound 

      Animated.timing(this.state.moveY2, { 
       toValue: 100, 
       duration: 500, 
       useNativeDrive: true, 
      }), 

      Animated.timing(this.state.moveY1, { 
       toValue: 50, 
       duration: 1000, 
       useNativeDrive: true, 
       easing: Easing.spring 
      }), // play sound 

      Animated.timing(this.state.moveY1, { 
       toValue: 100, 
       duration: 500, 
       useNativeDrive: true, 
      }), 


]).start() 

注:我知道如何使用反應本地聲音包打聲音,IM,我只是困惑,如何穩妥的打法,在每個計數。

回答

2

進入每個動畫的start()方法a callback can be added which is executed upon completion of the animation。的 因此,而不是在一個sequence寫作對你的動畫,你可以把它分解成更小的部分,像這樣:

// Run animation 

animation1.start(() => { 
    playSound1(); 
    Animated.sequence([ 
     animation2, 
     animation3, 
    ]).start(() => { 
     playSound2(); 
     Animated.sequence([ 
      animation4, 
      animation5, 
     ]).start(() => { 
      playSound3(); 
      animation6.start(); 
     }) 
    }) 
}); 

// Move animations into variables so that the execution of the animation is more readable 

const animation1 = Animated.timing(this.state.moveY3, { 
    toValue: 50, 
    duration: 1000, 
    useNativeDrive: true, 
    easing: Easing.spring 
}); 

const animation2 = Animated.timing(this.state.moveY3, { 
    toValue: 100, 
    duration: 100, 
    useNativeDrive: true, 
}), 

const animation3 = Animated.timing(this.state.moveY2, { 
    toValue: 50, 
    duration: 1000, 
    useNativeDrive: true, 
    easing: Easing.spring 
}), 

... 

通過移動第一位進入其他功能的一些東西,你可以減少嵌套了一下,使它更可讀..但它應該像那樣工作..

+0

真棒謝謝 –

+0

優秀的答案 –