如何在运行动画动画序列时添加副作用



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

法典:

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()
注意:我知道如何播放声音,我

使用反应原生声音包,我只是对如何在每次计数时播放声音感到困惑。

在每个动画的start()方法中,可以添加一个回调,该回调在动画完成后执行。因此,与其将所有动画都写成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
}),
...

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

最新更新