如何在运行动画序列时添加副作用(播放声音)?

时间:2017-06-18 13:45:10

标签: animation react-native

我正在尝试建立一个倒数计时器,并且对于每个计数我想播放声音。动画工作正常但我想知道我是否可以按顺序运行动画时播放声音。

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

注意:我知道如何播放声音,我使用的是反应本机声音包,我只是对如何在每次计数中播放声音感到困惑。

1 个答案:

答案 0 :(得分:2)

进入每个动画a callback can be added which is executed upon completion of the animationstart()方法。 因此,不是在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
}),

...

通过将第一位的某些内容移动到其他函数中,您可以减少嵌套并使其更具可读性......但它应该像那样工作..