I want to optimize a voice volume wave animation in React native

291 Views Asked by At

I tried it and also created successfully but there is performance issue. here is my code. This is main functionality of player

const audioRecorderPlayer = new AudioRecorderPlayer();
const VoiceIndicator = () => {
    const listRef = useRef(null)
    const [state, setState] = useState({ data: [] })

    const handleState = (key, value) => {
        state[key] = value
        setState({ ...state })
    }

    useEffect(() => {
        const remove = audioRecorderPlayer.addRecordBackListener((e) => {
            let arr = [...state.data]
            arr.push(e)
            handleState('data', arr)
            listRef.current?.scrollToEnd({ animated: true })
        });
        return () => audioRecorderPlayer.removeRecordBackListener(remove)
    }, [])
    const _renderDot = ({ item, index }) => <Dot item={item} index={index} />
    return (
        <>
            <Text style={{
                marginTop: 20,
                textAlign: 'center',
                fontSize: 20,
                fontWeight: '700'
            }}>{state.data.length}</Text>
            <ScrollView
                showsHorizontalScrollIndicator={false}
                // scrollEnabled={false}
                contentContainerStyle={{ justifyContent: 'center', height: 50 }}
                // ref={(e)=>e.} 
                ref={listRef}
                horizontal style={{ width: '80%', height: 50, alignSelf: 'center' }}>
                {
                    state.data.map((_, i) => {
                        return _renderDot({ item: _, index: i })
                    })
                }
            </ScrollView>
        </>
    )
}

This is Dot component.

const Dot = memo(({ item, index }) => {
    function calculateReturnValue(input) {
        if (input >= 30) {
            return 1;
        } else if (input >= 1) {
            return 31 - input;
        }
    }
    return (
        <View style={{ height: 50, justifyContent: 'center' }}>
            <Animated.View layout={Layout} entering={FadeIn} style={{ width: 5, height: calculateReturnValue(-item?.currentMetering), minHeight: 5, maxHeight: 30, margin: 2, backgroundColor: '#000', borderRadius: 10 }} />
        </View>
    )
}, () => true)

Right now I'm using react-native-audio-recorder-player package for recording and measuring audio. This code is working fine except performance drop.Yes I know that updating state again and again may cause frame drop but do you have any alternative idea how to make it very smooth. Please help me on this. This is the final result Voice Wave animation

0

There are 0 best solutions below