here `togglePlayPause` works only once. please check

import React, { useEffect, useState } from 'react';
import {
  View,
  Button,
  FlatList,
  Text,
  PermissionsAndroid,
  Platform,
  Alert,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';
import Sound from 'react-native-sound';
import RNFS from 'react-native-fs';

type AudioFile = RNFS.ReadDirItem;

const AudioPlayer: React.FC = () => {
  const [audioFiles, setAudioFiles] = useState<AudioFile[]>([]);
  const [currentSound, setCurrentSound] = useState<Sound | null>(null);
  const [isPlaying, setIsPlaying] = useState<boolean>(false);
  const [currentAudioIndex, setCurrentAudioIndex] = useState<number>(-1);

  // Request storage permission for Android
  const requestPermission = async (): Promise<boolean> => {
    if (Platform.OS === 'android') {
      try {
        const hasPermission = await PermissionsAndroid.check(
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        );
        if (hasPermission) {
          return true;
        }

        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
          {
            title: 'Permission to access storage',
            message: 'This app needs access to your storage to scan audio files.',
            buttonNeutral: 'Ask Me Later',
            buttonNegative: 'Cancel',
            buttonPositive: 'OK',
          },
        );
        return granted === PermissionsAndroid.RESULTS.GRANTED;
      } catch (err) {
        console.error('Failed to request permission:', err);
        return false;
      }
    }
    return true; // iOS does not require this permission
  };

  // Recursively scan directories for audio files
  const scanAudioFiles = async (dirPath: string): Promise<void> => {
    try {
      const dirExists = await RNFS.exists(dirPath);
      if (!dirExists) {
        console.log('Directory does not exist:', dirPath);
        Alert.alert('Error', 'The specified directory does not exist.');
        return;
      }

      const files = await RNFS.readDir(dirPath);
      const newAudioFiles: AudioFile[] = [];

      for (const file of files) {
        if (file.isFile() && (file.name.endsWith('.mp3') || file.name.endsWith('.wav'))) {
          console.log('Found audio file:', file.path);
          newAudioFiles.push(file);
        } else if (file.isDirectory()) {
          await scanAudioFiles(file.path);
        }
      }

      setAudioFiles((prevFiles) => [...prevFiles, ...newAudioFiles]);
    } catch (err) {
      console.error('Error scanning audio files:', err);
      Alert.alert('Error', 'Failed to scan audio files. Please check storage permissions.');
    }
  };

  // Play the selected audio file
  const playSound = async (path: string, index: number) => {
    console.log('Playing sound from path:', path);

    const fileExists = await RNFS.exists(path);
    if (!fileExists) {
      console.log('Audio file does not exist:', path);
      Alert.alert('Error', 'Audio file not found.');
      return;
    }

    // Stop and release the current sound if it exists
    if (currentSound) {
      currentSound.stop(() => {
        currentSound.release();
        console.log('Previous sound stopped and released');
      });
    }

    // Load and play the new sound
    const sound = new Sound(path, '', (error) => {
      if (error) {
        console.log('Failed to load the sound', error);
        Alert.alert('Error', 'Failed to load the audio file.');
        return;
      }

      console.log('Sound loaded successfully:', sound);
      setCurrentSound(sound);
      setCurrentAudioIndex(index);
      setIsPlaying(true);

      sound.setVolume(1.0); // Set to max volume
      sound.setCurrentTime(0); // Reset to start

      sound.play((success) => {
        if (success) {
          console.log('Successfully started playing');
        } else {
          console.log('Playback failed due to audio decoding errors');
          Alert.alert('Error', 'Playback failed.');
        }
        setIsPlaying(false); // Reset play state when playback ends
      });
    });
  };

  // Handle play/pause
  const togglePlayPause = () => {
    if (currentSound) {
      if (isPlaying) {
        currentSound.pause(() => {
          setIsPlaying(false);
          console.log('Sound paused');
        });
      } else {
        currentSound.play((success) => {
          if (success) {
            setIsPlaying(true);
            console.log('Sound resumed');
          } else {
            console.log('Playback failed');
          }
        });
      }
    }
  };

  // Handle next track
  const playNext = () => {
    if (currentAudioIndex < audioFiles.length - 1) {
      const nextIndex = currentAudioIndex + 1;
      playSound(audioFiles[nextIndex].path, nextIndex);
    }
  };

  // Handle previous track
  const playPrevious = () => {
    if (currentAudioIndex > 0) {
      const prevIndex = currentAudioIndex - 1;
      playSound(audioFiles[prevIndex].path, prevIndex);
    }
  };

  // Cleanup sound on component unmount
  useEffect(() => {
    return () => {
      if (currentSound) {
        currentSound.stop(() => {
          currentSound.release();
          console.log('Sound released on unmount');
        });
      }
    };
  }, [currentSound]);

  // Initialize the component
  useEffect(() => {
    const initialize = async () => {
      const permissionGranted = await requestPermission();
      if (permissionGranted) {
        const baseDir = Platform.OS === 'android' ? RNFS.ExternalStorageDirectoryPath : RNFS.DocumentDirectoryPath;
        await scanAudioFiles(baseDir);
      } else {
        Alert.alert(
          'Permission denied',
          'Cannot access storage without permission. Please grant storage access in app settings.',
        );
      }
    };

    initialize();
  }, []);

  return (
    <View style={styles.container}>
      {/* Audio List */}
      <FlatList
        data={audioFiles}
        keyExtractor={(item) => item.path}
        renderItem={({ item, index }) => (
          <View style={styles.audioItem}>
            <Text>{item.name}</Text>
            <Button title="Play" onPress={() => playSound(item.path, index)} />
          </View>
        )}
      />

      {/* Floating Player */}
      {currentAudioIndex !== -1 && (
        <View style={styles.floatingPlayer}>
          <TouchableOpacity onPress={playPrevious}>
            <Text>Prev</Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={togglePlayPause}>
            <Text>{isPlaying ? 'Pause' : 'Play'}</Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={playNext}>
            <Text>Next</Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 10,
  },
  audioItem: {
    margin: 10,
    padding: 10,
    backgroundColor: '#ccc',
    borderRadius: 5,
  },
  floatingPlayer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    backgroundColor: '#fff',
    padding: 10,
    borderTopWidth: 1,
    borderTopColor: '#ccc',
  },
});

export default AudioPlayer;